我试图在一个新的选项卡中打开一个URL,而不是弹出窗口。
我见过一些相关的问题,其中的回答大致如下:
window.open(url,'_blank');
window.open(url);
但没有一个对我有效,浏览器仍然试图打开一个弹出窗口。
我试图在一个新的选项卡中打开一个URL,而不是弹出窗口。
我见过一些相关的问题,其中的回答大致如下:
window.open(url,'_blank');
window.open(url);
但没有一个对我有效,浏览器仍然试图打开一个弹出窗口。
当前回答
要打开新选项卡并保持在同一位置,可以在新选项卡中打开当前页面,然后将旧选项卡重定向到新URL。
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
window.open(currentUrl , '_blank'); // Open window with the URL of the current page
location.href = newUrl; // Redirect the previous window to the new 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>
参考:使用JavaScript在新选项卡中打开URL
这可能是一个黑客,但在Firefox中,如果您指定第三个参数“fullscreen=yes”,它会打开一个新的窗口。
例如
<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>
它似乎实际上覆盖了浏览器设置。
这个问题有答案,但不是否定的。
我找到了一个简单的解决方法:
步骤1:创建不可见链接:
<a id=“yourId”href=“yourlink.html”target=“_blank”style=“display:none;”></a>
步骤2:以编程方式单击该链接:
document.getElementById(“yourId”).click();
干得好!这对我很有吸引力。
要打开新选项卡并保持在同一位置,可以在新选项卡中打开当前页面,然后将旧选项卡重定向到新URL。
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
window.open(currentUrl , '_blank'); // Open window with the URL of the current page
location.href = newUrl; // Redirect the previous window to the new URL
浏览器将自动将您移动到新打开的选项卡。看起来您的页面已重新加载,您将停留在同一页面上,但在新窗口上:
如果您只想打开外部链接(指向其他站点的链接),那么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');
}
});
});