4

Objective

I want to open a URL in a new tab/window in the EXACT same manner as target="_blank" would.

Code

I'm using a PHP condition which triggers the following JavaScript:

<script type="text/javascript">
window.open ("http://www.google.com/","_blank", "status=1,toolbar=1");
</script>

My problem

window.open is NOT THE SAME as target="_blank" hyperlinks.

  1. It presents an issue with pop-up blockers.
  2. The window requires parameters to look like what target="_blank" would have produced.
  3. Once the JavaScript runs, certain font colors of the containing document are lost.

My question

How do I EXACTLY simulate what's produced by target="_blank"?

7
  • 3
    You don't. Pop-up blockers check now-a-days to make sure that the action is user initiated otherwise it will block it. Commented Jan 25, 2012 at 0:16
  • Possible duplicate: stackoverflow.com/questions/1574008/… Commented Jan 25, 2012 at 0:16
  • @Ktash: What will it take for code to become 'user initiated'? Would it make sense to simulate the .click event? Commented Jan 25, 2012 at 1:09
  • @Travis J: Thanks but I've already seen that question. It doesn't account for the first difference I outlined. Commented Jan 25, 2012 at 1:10
  • Simulating the click won't work (that I know of at least). You would have to trigger once the user actually clicks. You won't be able to make code 'user initiated'. Unless you could 'trick' the user into click, or moving their mouse (not sure if this will work), or something. Commented Jan 25, 2012 at 1:15

1 Answer 1

1

Instead of opening the Window from JavaScript, use JavaScript to update a link's href and then trigger a click on the link. This way you'll get the exact same behavior as the user clicking the link.

Add a link to your page with an id and target="_blank". When you want to open a new window, update the href of this link and then trigger a click, like this (from here).

function clickLink(link) {
var cancelled = false;

if (document.createEvent) {
    var event = document.createEvent("MouseEvents");
    event.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0,
        false, false, false, false,
        0, null);
    cancelled = !link.dispatchEvent(event);
}
else if (link.fireEvent) {
    cancelled = !link.fireEvent("onclick");
}

if (!cancelled) {
    window.location = link.href;
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.