Open (url,’_ black’) ; 在 iMac/Safari 上无法工作

我已经建立了一个网页,让你选择一个网页名称从下拉列表,然后传输浏览器到该网页。传输的密码是

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

其中“ url”是选定的页面。

在 window.open 行之前的控制台日志显示如下内容:

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

然后浏览器会在一个新标签页中打开页面。

这在 Windows7上适用于所有浏览器,包括 Safari。

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

有人知道为什么 iMac/Safari 不这么做吗?

164347 次浏览

There's a setting in Safari under "Tabs" that labeled Open pages in tabs instead of windows: with a drop down with a few options. I'm thinking yours may be set to Always. Bottom line is you can't rely on a browser opening a new window.

To use window.open() in safari you must put it in an element's onclick event attribute.

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

The correct syntax is window.open(URL,WindowTitle,'_blank') All the arguments in the open must be strings. They are not mandatory, and window can be dropped. So just newWin=open() works as well, if you plan to populate newWin.document by yourself. BUT you MUST use all the three arguments, and the third one set to '_blank' for opening a new true window and not a tab.

Taken from the accepted answers comment by Steve on Dec 20, 2013:

Actually, there's a very easy way to do it: just click off "Block popup windows" in the iMac/Safari browser and it does what I want.

To clarify, when running Safari on Mac OS X El Capitan:

  1. Safari -> Preferences
  2. Security -> Uncheck 'Block pop-up windows'

Safari is blocking any call to window.open() which is made inside an async call.

The solution that I found to this problem is to call window.open before making an asnyc call and set the location when the promise resolves.

var windowReference = window.open();


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

window.location.assign(url) this fixs the window.open(url) issue in ios devices

You can't rely on window.open because browsers may have different policies. I had the same issue and I used the code below instead.

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

Open link in a new tab, programatically with JavaScript for: safari, mobile safari and other browsers:

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


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

Using setTimeout

Wrapping your window.open(url, '_blank') line of code in the async function with a setTimeout works as well,

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

setTimeout code runs on the main thread, instead of the asynchronous one. Tested in Chrome and Safari.

This should work: window.location.assign(url); Usually it is important to save the state, before leaving the page, so have this in mind as well.