window.open(url, '_blank');无法在 iMac/Safari 上工作

问题描述 投票:0回答:11

我构建了一个网页,让您从下拉列表中选择页面名称,然后将浏览器转移到该页面。进行转账的代码是

if (url){
    window.open(url, '_blank');
} 

其中“url”是所选页面。

window.open 行之前的控制台日志打印如下内容:

    executing: window.open('http://www.mywebsite.com/44/threats.html', '_blank')

然后浏览器会在新选项卡中打开页面。

这在 Windows 7 上的所有浏览器(包括 Safari)上都可以正常工作。

在 iMac 上,它适用于 Firefox,但不适用于 Safari。

有谁知道为什么 iMac/Safari 不会这样做?

javascript macos safari
11个回答
282
投票

Safari 正在阻止任何在异步调用中对 window.open() 进行的调用。

我发现这个问题的解决方案是在进行 asnyc 调用之前调用 window.open 并在 Promise 解析时设置位置。

var windowReference = window.open();

myService.getUrl().then(function(url) {
     windowReference.location = url;
});

48
投票

使用setTimeout

编辑:有些人报告说此方法在最新的 Safari 上不再适用。

使用 setTimeout 将

window.open(url, '_blank')
代码行包装在异步函数中也可以,

setTimeout(() => {
    window.open(url, '_blank');
})

setTimeout 代码在主线程上运行,而不是异步线程。 在 Chrome 和 Safari 中测试。


24
投票

要在 safari 中使用 window.open(),您必须将其放入元素的 onclick 事件属性中。

例如:

<button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>


22
投票

您不能依赖

window.open
,因为浏览器可能有不同的策略。我遇到了同样的问题,我使用了下面的代码。

let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = <your_url>;
a.download = <your_fileName>;
a.click();
document.body.removeChild(a);

14
投票

window.location.assign(url)
这解决了ios设备中的
window.open(url)
问题


13
投票

摘自 Steve 于 2013 年 12 月 20 日接受的答案评论:

实际上,有一个非常简单的方法:只需在 iMac/Safari 浏览器中单击“阻止弹出窗口”即可完成我想要的操作。

澄清一下,在 Mac OS X El Capitan 上运行 Safari 时:

  1. Safari -> 偏好设置
  2. 安全 -> 取消选中“阻止弹出窗口”

7
投票

使用 JavaScript 以编程方式在新选项卡中打开链接:safari、mobile safari 和其他浏览器:

const link = 'https://google.com';

const a = document.createElement("a");
a.setAttribute('href', link);
a.setAttribute('target', '_blank');
a.click();

1
投票

Safari 中的“选项卡”下有一个标记为

Open pages in tabs instead of windows:
的设置,其中有一个带有几个选项的下拉菜单。我想你的可能被设置为
Always
。最重要的是,您不能依赖浏览器打开新窗口。


1
投票

它不会工作,因为 safari 不支持它。

检查 MDN 文档的兼容性 - https://developer.mozilla.org/en-US/docs/Web/API/Window/open#browser_compatibility


0
投票

这应该有效:

window.location.assign(url);
通常,在离开页面之前保存状态很重要,所以也要记住这一点。


-14
投票

正确的语法是

window.open(URL,WindowTitle,'_blank')
open 中的所有参数都必须是字符串。它们不是强制性的,并且可以删除窗口。因此,如果您打算自己填充 newWin.document,则
newWin=open()
也可以。 但您必须使用所有三个参数,并将第三个参数设置为
'_blank'
以打开一个新的真实窗口而不是选项卡。

© www.soinside.com 2019 - 2024. All rights reserved.