20 September 2013

Javascript: open new named tab with window.open

Often we come to a situation where we want to open a url in new tab. At the same time we want to prevent user end up opening many tabs, where we want to open url in same named tab.

1. In modern browsers, window.open will open in a new tab rather than a popup.

2. You can force a browser to use a new window (‘popup’) by specifying options in the 3rd parameter

3. If the window.open call was not part of a user-initiated event, it’ll open in a new window.

4. A “user initiated event” does not have to the same function call – but it must originate in the function invoked by a user click

5. If a user initiated event delegates or defers a function call (in an event listener or delegate not bound to the click event, or by using setTimeout for example), it loses it’s status as “user initiated”

6. Some popup blockers will allow windows opened from user initiated events, but not those opened otherwise.

7. If any popup is blocked, those normally allowed by a blocker (via user initiated events) will sometimes also be blocked.

Forcing a window to open in a new browser instance, instead of a new tab:

window.open('http://www.google.com', '', 'width=1024');

The following would qualify as a user-initiated event, even though it calls another function:

function o(){
$('button').addEvent('click', o);

The following would not qualify as a user-initiated event, since the setTimeout defers it:

function g(){
  setTimeout(o, 1);
function o(){
$('button').addEvent('click', g);

Solution example:

No comments: