zuluk zuluk - 28 days ago 8
HTML Question

window.open on a-tag for new tab

I am using this code to open a new tab:

<a href="javascript:window.open('https://example.com','_blank')">linktext</a>


The new page is also loaded within a new tab however at the source page it is shown
[object]
instead of the link. What is wrong?

I do not want to use

<a href="https://example.com" target="_blank")">linktext</a>


because I generate a list of links and the target page is called differently for each link. The most flexible way for me is to use the give Syntax.

EDIT:
This is the generated linklist:

<a href="javascript:window.open('https://example.com','_blank')">linktext 1</a>
<a href="javascript:jsfunc1(param1)">linktext 2</a>
<a href="javascript:jsfunc2(param2,param3)">linktext 3</a>


The href attribute is generated. I get a from a table.

Answer

The point of a javascript: scheme URL is to generate a replacement page from JavaScript. It isn't designed to run JavaScript in response to a client while leaving the page alone — that is what event handlers are for.

The new "page" you are seeing is the result of converting the reference to the new window to a string.

This is best avoided by not using JavaScript for this:

<a href="https://example.com" target='_blank'>linktext</a>

You can also do it by avoiding using javascript: scheme URIs and binding your JS separately (with a sensible fallback in the href):

<a href="https://example.com">linktext</a>

<script>
    document.querySelector("a").addEventListener("click", your_function);
    function your_function(evt) {
        evt.preventDefault();
        // Then do whatever else you want the function to do
    }
</script>

If you really want to use the JavaScript URL scheme (which, as I suggested above, is a dirty hack), you can ensure that the script returns nothing using the void operator:

<a href="javascript:void (window.open('https://example.com','_blank'))">linktext</a>