window.open() call is redirected in Google Sites

832 views Asked by At

So I have a page in Google sites with the following code inside an HTML Box:

<a id="resource-link" href="#">My Link</a>

<script type="text/javascript">
   document.getElementById("resource-link").addEventListener("click", function(e){
      e.preventDefault()
      window.open("http://www.google.com","_blank");
   });
</script>

I have also tried using the onclick attribute rather than addEventListener()

Works fine in this JSFiddle.

When this code is put into an HTML Box, clicking the link results in opening a new tab (what I want), however before loading http://www.google.com, it is redirected to the url of the original page with the link on it.

P.S. I really hate Google Sites and all its nonsense.

UPDATE: the reason I am not using a simple <a href="..."></a> is because I need to open multiple tabs with a single click. The single call to window.open(google) is just an example.

UPDATE 2:

changing the code to:

<a onClick="open_resources()">My Link</a>

<script type="text/javascript">
  var open_resources = function(){
    window.open("http://www.google.com","_blank");
  };
</script>

results in the following error:

Uncaught script error: Uncaught TypeError: Expected property "open" to be a function, not undefined: undefined in source: "<click handler>" at line: -1
2

There are 2 answers

0
mpallansch On

You could change the element from an anchor to a span and style it to look like a link:

head

<style>
    #resource-link{
        color: blue;
        cursor: pointer;
        text-decoration: underline;
    }
</style>

body

<span id="resource-link">My Link</span>

<script type="text/javascript">
  document.getElementById("resource-link").addEventListener("click", function(e){
     window.open("http://www.google.com","_blank");
  });
</script>
5
mpallansch On

Another answer could be to have the first link in the anchor tag and other ones in the click handler, like this:

<a id="resource-link" href="http://www.site1.com" target="_blank">My Link</a>

<script type="text/javascript">
   document.getElementById("resource-link").addEventListener("click", function(e){
      window.open("http://www.site2.com","_blank");
      window.open("http://www.site3.com","_blank");
      // ...
   });
</script>