'window.open' blocked by Chrome with change event

柔情痞子 提交于 2019-12-13 14:05:54

问题


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.)


回答1:


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.




回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/30466129/window-open-blocked-by-chrome-with-change-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!