我试图在一个新的选项卡中打开一个URL,而不是弹出窗口。
我见过一些相关的问题,其中的回答大致如下:
window.open(url,'_blank');
window.open(url);
但没有一个对我有效,浏览器仍然试图打开一个弹出窗口。
我试图在一个新的选项卡中打开一个URL,而不是弹出窗口。
我见过一些相关的问题,其中的回答大致如下:
window.open(url,'_blank');
window.open(url);
但没有一个对我有效,浏览器仍然试图打开一个弹出窗口。
当前回答
这将创建一个虚拟的a元素,并为其提供target=“_blank”,因此它将在一个新选项卡中打开,为其提供适当的URL href,然后单击它。
function openInNewTab(href) {
Object.assign(document.createElement('a'), {
target: '_blank',
rel: 'noopener noreferrer',
href: href,
}).click();
}
然后你可以像这样使用它:
openInNewTab("https://google.com");
重要说明:
这必须在所谓的“可信事件”回调过程中调用,例如,在单击事件期间(在回调函数中不需要直接调用,但在单击操作期间)。否则,浏览器将阻止打开新页面。
如果您在某个随机时刻手动调用它(例如,在一段时间内或在服务器响应之后),它可能会被浏览器阻止(这很有道理,因为这会带来安全风险,并可能导致用户体验不佳)。
其他回答
(function(a) {
document.body.appendChild(a);
a.setAttribute('href', location.href);
a.dispatchEvent((function(e) {
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))))
}(document.createElement('a')))
下面是一个如何将其放入HTML标记的示例
<button onClick="window.open('https://stackoverflow.com/','_blank')">Stackoverflow</button>
这对我有效。只需阻止事件,将URL添加到<a>标记,然后在该标记上触发单击事件。
JavaScript
$('.myBtn').on('click', function(event) {
event.preventDefault();
$(this).attr('href', "http://someurl.com");
$(this).trigger('click');
});
HTML
<a href="#" class="myBtn" target="_blank">Go</a>
这种方式与以前的解决方案类似,但实施方式不同:
.social_icon->CSS类
<div class="social_icon" id="SOME_ID" data-url="SOME_URL"></div>
$('.social_icon').click(function(){
var url = $(this).attr('data-url');
var win = window.open(url, '_blank'); ///similar to above solution
win.focus();
});
是否在新选项卡或新窗口中打开URL,实际上由用户的浏览器首选项控制。无法在JavaScript中覆盖它。
window.open()的行为取决于它的使用方式。如果它是作为用户操作的直接结果调用的,让我们假设单击一个按钮,它应该可以正常工作并打开一个新的选项卡(或窗口):
const button = document.querySelector('#openTab');
// add click event listener
button.addEventListener('click', () => {
// open a new tab
const tab = window.open('https://attacomsian.com', '_blank');
});
但是,如果您尝试从AJAX请求回调打开新选项卡,浏览器将阻止它,因为它不是直接的用户操作。
要绕过弹出窗口阻止程序并从回调中打开新选项卡,这里有一个小技巧:
const button = document.querySelector('#openTab');
// add click event listener
button.addEventListener('click', () => {
// open an empty window
const tab = window.open('about:blank');
// make an API call
fetch('/api/validate')
.then(res => res.json())
.then(json => {
// TODO: do something with JSON response
// update the actual URL
tab.location = 'https://attacomsian.com';
tab.focus();
})
.catch(err => {
// close the empty window
tab.close();
});
});