我正在尝试在新标签中打开 URL,而不是弹出窗口。
我已经看到相关的问题,其中的响应看起来像:
window.open(url,'_blank');
window.open(url);
但是它们都不适合我,浏览器仍然试图打开一个弹出窗口。
这是一个技巧,
function openInNewTab(url) {
window.open(url, '_blank').focus();
}
//or just
window.open(url, '_blank').focus();
在大多数情况下,这应该直接在链接的 onclick
处理程序中发生,以防止弹出窗口阻止程序和默认的“新窗口”行为。您可以这样做,或者向您的 DOM
对象添加一个事件侦听器。
<div onclick="openInNewTab('www.test.com');">Something To Click On</div>
http://www.tutsplanet.com/open-url-new-tab-using-javascript/
作者无法选择在新选项卡而不是新窗口中打开;这是用户偏好。 (请注意,大多数浏览器中的默认用户首选项是针对新选项卡的,因此在未更改该首选项的浏览器上进行的简单测试不会证明这一点。)
CSS3 提出了 target-new,但提出了 the specification was abandoned。
The reverse is not true;通过在 window.open()
的第三个参数中为窗口指定某些窗口功能,您可以在偏好选项卡时触发一个新窗口。
window.open
告诉浏览器打开新内容,然后浏览器打开在其设置中选择的内容 - 选项卡或窗口。在您测试的浏览器中,将设置更改为在新窗口而不是选项卡中打开,您会看到其他人的解决方案是错误的。
如果实际点击事件没有发生,window.open()
将不会在新标签中打开。在给出的示例中,URL 是在实际点击事件中打开的。 如果用户在浏览器中进行了适当的设置,这将起作用。
<a class="link">Link</a>
<script type="text/javascript">
$("a.link").on("click",function(){
window.open('www.yourdomain.com','_blank');
});
</script>
同样,如果您尝试在 click 函数中执行 Ajax 调用并希望在成功时打开一个窗口,请确保您在执行 Ajax 调用时设置了 async : false
选项。
async: false
在 Chrome 中不起作用。要通过回调打开一个新窗口,您需要在发送 HTTP 请求之前先打开一个空窗口,然后再更新它。这是一个good hack。
这将创建一个虚拟 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");
重要的提示:
这必须在所谓的“可信事件”回调期间调用 - 例如。在点击事件期间(直接在回调函数中不需要,但在点击动作期间)。否则浏览器会阻止打开新页面
如果您在某个随机时刻(例如,在某个时间间隔内或在服务器响应之后)手动调用它 - 它可能会被浏览器阻止(这是有道理的,因为它会带来安全风险并可能导致糟糕的用户体验)
$('<a />',{'href': url, 'target', '_blank'}).get(0).click();
Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();
浏览器在处理window.open
方面有不同的行为
您不能期望所有浏览器的行为都相同。 window.open
不能可靠地跨浏览器在新标签页上打开弹出窗口,而且它还取决于用户的偏好。
在Internet Explorer(11)上,例如用户可以选择在新窗口或新标签页中打开弹窗,不能通过window.open
强制Internet Explorer 11以某种方式打开弹窗,正如 Quentin's answer 中提到的那样。
至于 Firefox (29),window.open(url, '_blank')
的行为取决于浏览器的选项卡首选项, 尽管您仍然可以通过指定宽度和高度(参见下面的“Chrome”部分)。
互联网浏览器 (11)
您可以将 Internet Explorer 设置为在新窗口中打开弹出窗口:
https://i.stack.imgur.com/IYWRUm.png
之后,尝试运行 window.open(url)
和 window.open(url, '_blank')
。观察页面在新窗口中打开,而不是在新选项卡中。
火狐 (29)
您还可以设置选项卡首选项以打开新窗口,并查看相同的结果。
铬合金
看起来 Chrome(版本 34)没有任何用于选择在新窗口或新标签页中打开弹出窗口的设置。虽然,我们讨论了一些方法(编辑注册表)in this question。
在 Chrome 和 Firefox 中,指定宽度和高度将强制弹出窗口(如答案 here 中所述),即使用户已将 Firefox 设置为在新标签页中打开新窗口
let url = 'https://stackoverflow.com'
window.open(url, '', 'width=400, height=400')
但是,在 Internet Explorer 11 中,如果在浏览器首选项中选择了选项卡,则相同的代码将始终在新选项卡中打开链接,指定宽度和高度不会强制弹出新窗口。
在 Chrome 中,似乎 window.open
在 onclick
事件中使用时会打开一个新标签,而在浏览器控制台 (as noted by other people) 中使用时会打开一个新窗口,然后弹出-ups 在指定宽度和高度时打开。
补充阅读:window.open
documentation。
如果您使用 window.open(url, '_blank')
,它将在 Chrome 上被阻止(弹出窗口阻止程序)。
尝试这个:
//With JQuery
$('#myButton').click(function () {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
});
使用纯 JavaScript,
document.querySelector('#myButton').onclick = function() {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
};
the request was made in a sandboxed frame whose 'allow-popups' permission is not set
而被阻塞
我使用以下,效果很好!
window.open(url, '_blank').focus();
为了详细说明史蒂文斯皮尔伯格的回答,我在这种情况下这样做了:
$('a').click(function() {
$(this).attr('target', '_blank');
});
这样,就在浏览器跟随链接之前,我正在设置目标属性,因此它将使链接在新选项卡或窗口中打开(取决于用户的设置)。
jQuery中的一行示例:
$('a').attr('target', '_blank').get(0).click();
// The `.get(0)` must be there to return the actual DOM element.
// Doing `.click()` on the jQuery object for it did not work.
这也可以仅使用本机浏览器 DOM API 来完成:
document.querySelector('a').setAttribute('target', '_blank');
document.querySelector('a').click();
一个有趣的事实是,如果用户没有调用该操作(单击按钮或其他东西)或者它是异步的,则无法打开新选项卡,例如,这不会在新选项卡中打开:
$.ajax({
url: "url",
type: "POST",
success: function() {
window.open('url', '_blank');
}
});
但这可能会在新选项卡中打开,具体取决于浏览器设置:
$.ajax({
url: "url",
type: "POST",
async: false,
success: function() {
window.open('url', '_blank');
}
});
<script>open('http://google.com')</script>
保存到 .html
文件并在最新版本的 Firefox 的全新安装中打开它;您会观察到 Firefox 在新选项卡中愉快地打开 Google(可能是在您告诉它允许弹出窗口之后),而不是新窗口。
是在新标签页还是新窗口中打开 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 请求回调打开新选项卡,浏览器将阻止它,因为它不是直接的用户操作。
要绕过弹出窗口阻止程序并从回调中打开一个新标签,这里有一个 little hack:
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();
});
});
只需省略 strWindowFeatures
参数将打开一个新选项卡,除非浏览器设置覆盖它(浏览器设置胜过 JavaScript)。
新窗户
var myWin = window.open(strUrl, strWindowName, [strWindowFeatures]);
新标签
var myWin = window.open(strUrl, strWindowName);
- 或者 -
var myWin = window.open(strUrl);
function openTab(url) {
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
document.body.appendChild(link);
link.click();
link.remove();
}
(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')))
如果您尝试从自定义功能打开新选项卡,这与浏览器设置无关。
在此页面中,打开 JavaScript 控制台并键入:
document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").click();
无论您的设置如何,它都会尝试打开一个弹出窗口,因为“点击”来自自定义操作。
为了表现得像链接上的实际“鼠标点击”,您需要按照 @spirinvladimir's advice 并真正创建它:
document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
false, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))));
这是一个完整的示例(不要在 jsFiddle 或类似的在线编辑器上尝试,因为它不会让您从那里重定向到外部页面):
<!DOCTYPE html>
<html>
<head>
<style>
#firing_div {
margin-top: 15px;
width: 250px;
border: 1px solid blue;
text-align: center;
}
</style>
</head>
<body>
<a id="my_link" href="http://www.google.com"> Go to Google </a>
<div id="firing_div"> Click me to trigger custom click </div>
</body>
<script>
function fire_custom_click() {
alert("firing click!");
document.getElementById("my_link").dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, /* type, canBubble, cancelable, view */
0, 0, 0, 0, 0, /* detail, screenX, screenY, clientX, clientY */
false, false, false, false, /* ctrlKey, altKey, shiftKey, metaKey */
0, null); /* button, relatedTarget */
return e
}(document.createEvent('MouseEvents'))));
}
document.getElementById("firing_div").onclick = fire_custom_click;
</script>
</html>
w = window.open("placeholder"); $.ajax(...ajax call that returns the url...) success (...w.location = data.url...)
您可以使用 form
的技巧:
$(function () {
$('#btn').click(function () {
openNewTab("http://stackoverflow.com")
return false;
});
});
function openNewTab(link) {
var frm = $('<form method="get" action="' + link + '" target="_blank"></form>')
$("body").append(frm);
frm.submit().remove();
}
name
为键的表单元素中。 value
作为查询参数中所有参数的值。然后提交表格
jQuery
$('<a />',{'href': url, 'target': '_blank'}).get(0).click();
JS
Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();
或者您可以创建一个链接元素并单击它...
var evLink = document.createElement('a');
evLink.href = 'http://' + strUrl;
evLink.target = '_blank';
document.body.appendChild(evLink);
evLink.click();
// Now delete it
evLink.parentNode.removeChild(evLink);
这不应该被任何弹出窗口阻止程序阻止......希望如此。
不要使用 target="_blank"
在我的情况 meaningfulName
中,始终使用该窗口的特定名称,在这种情况下,您可以节省处理器资源:
button.addEventListener('click', () => {
window.open('https://google.com', 'meaningfulName')
})
这样,当您单击按钮例如 10 次时,浏览器将始终在一个新选项卡中重新呈现它,而不是在 10 个不同的选项卡中打开它,这将消耗更多资源。
您可以在 MDN
上阅读更多相关信息。
这个问题有答案,但不是没有。
我找到了一个简单的解决方法:
第 1 步:创建一个不可见的链接:
<a id="yourId" href="yourlink.html" target="_blank" style="display: none;"></a>
第 2 步:以编程方式单击该链接:
document.getElementById("yourId").click();
干得好!对我很有魅力。
要打开新标签并保持在同一位置,您可以在新标签中打开当前页面,并将旧标签重定向到新网址。
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
window.open(currentUrl , '_blank'); // open window with url of current page
location.href = newUrl; // redirect the previous window to the new url
浏览器会自动将您移动到新打开的选项卡。看起来您的页面已重新加载,您将停留在同一页面但在新窗口中
https://i.stack.imgur.com/RCgV9.gif
如何创建一个 _blank
作为 target
属性值和 url
作为 href
的 <a>
,其样式为 display:hidden 并带有一个子元素?然后添加到 DOM,然后在子元素上触发 click 事件。
更新
那是行不通的。浏览器阻止默认行为。它可以以编程方式触发,但它不遵循默认行为。
亲自检查并查看:http://jsfiddle.net/4S4ET/
这可能是一个 hack,但在 Firefox 中,如果您指定第三个参数“fullscreen=yes”,它会打开一个全新的窗口。
例如,
<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>
它似乎实际上覆盖了浏览器设置。
window.open(url)
将在新的浏览器选项卡中打开 url。下面是它的 JS 替代品
let a= document.createElement('a');
a.target= '_blank';
a.href= 'https://support.wwf.org.uk/';
a.click(); // we don't need to remove 'a' from DOM because we not add it
这是工作 example(stackoverflow 片段不允许打开新标签)
有很多答案副本建议使用“_blank”作为目标,但是我发现这不起作用。正如 Prakash 所说,这取决于浏览器。但是,您可以向浏览器提出某些建议,例如窗口是否应该有位置栏。
如果您提出了足够的“类似标签的东西”,您可能会得到一个标签,as per Nico's answer to this more specific question for chrome:
window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
免责声明:这不是灵丹妙药。它仍然取决于用户和浏览器。现在,至少您已经为您希望窗口的外观指定了另一种偏好。
从 Firefox (Mozilla) 扩展中打开一个新选项卡如下所示:
gBrowser.selectedTab = gBrowser.addTab("http://example.com");
这种方式与上述解决方案类似,但实现方式不同
.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 添加到 <a>
tag
然后触发该 tag
上的点击事件。
Js
$('.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>
我将在一定程度上同意以下人的观点(此处转述):“对于现有网页中的链接,如果新页面与相同的网站属于同一网站,则浏览器将始终在新选项卡中打开该链接。现有网页。”至少对我来说,这个“一般规则”适用于 Chrome、Firefox、Opera、IE、Safari、SeaMonkey 和 Konqueror。
无论如何,有一种不太复杂的方法可以利用其他人所呈现的内容。假设我们正在谈论您自己的网站(下面的“thissite.com”),您想要控制浏览器的操作,那么,下面,您希望“specialpage.htm”为空,其中根本没有 HTML(节省从服务器发送数据的时间!)。
var wnd, URL; //global variables
//specifying "_blank" in window.open() is SUPPOSED to keep the new page from replacing the existing page
wnd = window.open("http://www.thissite.com/specialpage.htm", "_blank"); //get reference to just-opened page
//if the "general rule" above is true, a new tab should have been opened.
URL = "http://www.someothersite.com/desiredpage.htm"; //ultimate destination
setTimeout(gotoURL(),200); //wait 1/5 of a second; give browser time to create tab/window for empty page
function gotoURL()
{ wnd.open(URL, "_self"); //replace the blank page, in the tab, with the desired page
wnd.focus(); //when browser not set to automatically show newly-opened page, this MAY work
}
如果您只想打开外部链接(指向其他站点的链接),那么这部分 JavaScript/jQuery 效果很好:
$(function(){
var hostname = window.location.hostname.replace('www.', '');
$('a').each(function(){
var link_host = $(this).attr('hostname').replace('www.', '');
if (link_host !== hostname) {
$(this).attr('target', '_blank');
}
});
});
不定期副业成功案例分享
window.open()
时打开 new 窗口,请为windowName
使用特殊值_blank
。