简体   繁体   中英

'window.open' blocked by Chrome with change event

I am trying to open a window based on an onChange event on a select element without getting blocked by Chrome's popup blocker.

The problem is demonstrated here.

https://jsfiddle.net/yyfe0824/1/

<select class="dropdown-select" onChange="window.open('https://www.google.com');">
    <option value="uno">Uno</option>
    <option value="dos">Dos</option>
    <option value="tres">Tres</option>
</select>

<input type="button" onClick="window.open('https://www.google.com');" value="click me">

There is no problem with a window.open call on the 'click me' button, but if you try to change the select dropdown, chrome will block the popup.

So far, answers to this problem have been specific to the onClick event. Doing research reveals that Chrome will block popups if it detects that it is not user triggered via some sort of handler, so I'm specifically trying to call the function inline, rather than using another named function.

Is this the intended behavior of window.open, specifically for onChange and if so, is there any particular workaround? (Aside from changing the structure to be a click event in the first place.)

That is by design, the only time browsers don't block window.open is when you are handling a click event.

My suggestion is to provide a link that changes when users select from the dropdown.

I advise against opening a popup because users don't expect a popup when you select from a drop down, that is why popup blockers don't typically allow this. Even if you find something that works in a browser ( https://jsfiddle.net/yyfe0824/5/ in Firefox), it could break in the future.

You should be able to work around this by having click wired up and simply determine if the new selected item matches the previous selected item.

I've edited the previous JSFiddle to make it work.

dropdown.addEventListener('click', Foo);    
function Foo(e)
{
    var selectedIndex = dropdown.selectedIndex;
    if(selectedIndex !== oldSelectedIndex)
    {
        var val = dropdown.options[selectedIndex].value;
        var opened = window.open(val);
        oldSelectedIndex = selectedIndex;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM