【问题标题】:window.open blocked as popup during user actionwindow.open 在用户操作期间被阻止为弹出窗口
【发布时间】:2021-07-12 19:36:52
【问题描述】:

Firefox 正在阻止我使用 window.open 并阻止它,就好像它是一个不需要的弹出窗口一样。

我有一个带有按钮的用户界面。

当按钮被按下时,我调用一个服务来获取一些数据,然后将该调用的结果用作我 window.open() 到的 url 的输入。

伪代码看起来像:

onClick = (selectedAccount, $event){
  this.serviceBroker.getUrl(selectedAccount).then(data => window.open(data.url, '_blank', 'noreferrer'));
}

上面的代码将在 Firefox 中显示一条消息popup blocked would you like to allow this popup?
我假设这是因为对 window.open 的调用被传递到没有用户操作上下文的服务中。

如果我将代码更改为:

onClick = selectedAccount, $event){
  window.open(<hardcoded_url>,'_blank', 'noreferrer');
}

然后新标签打开,我没有收到不需要的popup blocked

我尝试将函数的上下文与 $event 绑定为 promise 的解析调用,但没有帮助

let test = data => window.open(data.url, '_blank', 'noreferrer');
onClick = (selectedAccount, $event){
  this.serviceBroker.getUrl(selectedAccount).then(test.bind(this));
}

这仅在 Firefox 中发生,并且在 IE、Chrome 或 Edge 中不会阻止弹出窗口。

【问题讨论】:

    标签: javascript angular firefox


    【解决方案1】:

    所有浏览器都支持 window.open() 来显示弹出窗口,但有一些规则。该窗口应因用户操作(例如,单击按钮)而打开。不过,如果你在按钮点击事件中添加异步调用并尝试在 then/callback 中打开弹出窗口,它不再被视为用户操作,这样的弹出窗口将被屏蔽

    const popUp = (url) => {
           const isOpen = window.open(url, '_blank')
        
            if(isOpen==null){
               return true;
            }
    
           return false;
       };
    
     this.serviceBroker.getUrl(selectedAccount).then(data => popUp(data.url));
    

    我尝试在单击按钮时保持异步调用,但它仍然被阻止。

    https://codesandbox.io/s/zen-field-1srdo?file=/src/Moondc.js

    最好的解决方法是先打开,然后在异步操作完成后用内容填充它。

    let popUp = window.open(url, '_blank');
    
    this.serviceBroker.getUrl(selectedAccount).then(data => {
                popUp.document.write(data.url);
                popUp.focus();
    });
    

    或者简单地说,

    let popUp= window.open(...);
    
     this.serviceBroker.getUrl(selectedAccount).then(data => {
              popUp.location = data.url;
        });
    

    【讨论】:

    • 这可行,但我们需要noreferrer 的附加安全性,因此我无法将弹出窗口的引用存储在变量中。
    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2011-04-25
    • 2014-03-14
    相关资源
    最近更新 更多