我构建了一个网页,让您从下拉列表中选择页面名称,然后将浏览器转移到该页面。进行转账的代码是
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 不会这样做?
Safari 正在阻止任何在异步调用中对 window.open() 进行的调用。
我发现这个问题的解决方案是在进行 asnyc 调用之前调用 window.open 并在 Promise 解析时设置位置。
var windowReference = window.open();
myService.getUrl().then(function(url) {
windowReference.location = url;
});
编辑:有些人报告说此方法在最新的 Safari 上不再适用。
使用 setTimeout 将
window.open(url, '_blank')
代码行包装在异步函数中也可以,
setTimeout(() => {
window.open(url, '_blank');
})
setTimeout 代码在主线程上运行,而不是异步线程。 在 Chrome 和 Safari 中测试。
要在 safari 中使用 window.open(),您必须将其放入元素的 onclick 事件属性中。
例如:
<button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>
您不能依赖
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);
window.location.assign(url)
这解决了ios设备中的window.open(url)
问题
摘自 Steve 于 2013 年 12 月 20 日接受的答案评论:
实际上,有一个非常简单的方法:只需在 iMac/Safari 浏览器中单击“阻止弹出窗口”即可完成我想要的操作。
澄清一下,在 Mac OS X El Capitan 上运行 Safari 时:
使用 JavaScript 以编程方式在新选项卡中打开链接:safari、mobile safari 和其他浏览器:
const link = 'https://google.com';
const a = document.createElement("a");
a.setAttribute('href', link);
a.setAttribute('target', '_blank');
a.click();
Safari 中的“选项卡”下有一个标记为
Open pages in tabs instead of windows:
的设置,其中有一个带有几个选项的下拉菜单。我想你的可能被设置为Always
。最重要的是,您不能依赖浏览器打开新窗口。
它不会工作,因为 safari 不支持它。
检查 MDN 文档的兼容性 - https://developer.mozilla.org/en-US/docs/Web/API/Window/open#browser_compatibility
这应该有效:
window.location.assign(url);
通常,在离开页面之前保存状态很重要,所以也要记住这一点。
正确的语法是
window.open(URL,WindowTitle,'_blank')
open 中的所有参数都必须是字符串。它们不是强制性的,并且可以删除窗口。因此,如果您打算自己填充 newWin.document,则 newWin=open()
也可以。
但您必须使用所有三个参数,并将第三个参数设置为 '_blank'
以打开一个新的真实窗口而不是选项卡。