我试图在一个新的选项卡中打开一个URL,而不是弹出窗口。
我见过一些相关的问题,其中的回答大致如下:
window.open(url,'_blank');
window.open(url);
但没有一个对我有效,浏览器仍然试图打开一个弹出窗口。
我试图在一个新的选项卡中打开一个URL,而不是弹出窗口。
我见过一些相关的问题,其中的回答大致如下:
window.open(url,'_blank');
window.open(url);
但没有一个对我有效,浏览器仍然试图打开一个弹出窗口。
当前回答
我使用了以下方法,效果很好!
window.open(url, '_blank').focus();
其他回答
function openTab(url) {
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
document.body.appendChild(link);
link.click();
link.remove();
}
如果链接位于同一域(同一网站),浏览器将始终在新选项卡中打开该链接。如果链接在其他域上,它将在新的选项卡/窗口中打开,具体取决于浏览器设置。
因此,根据这一点,我们可以使用:
<a class="my-link" href="http://www.mywebsite.com" rel="http://www.otherwebsite.com">new tab</a>
并添加一些jQuery代码:
jQuery(document).ready(function () {
jQuery(".my-link").on("click",function(){
var w = window.open('http://www.mywebsite.com','_blank');
w.focus();
w.location.href = jQuery(this).attr('rel');
return false;
});
});
所以,首先用_blank target在同一个网站上打开新窗口(它将在新选项卡中打开),然后在新窗口中打开您想要的网站。
不要使用target=“_blank”
始终为该窗口使用一个特定的名称,在我的情况下是指fulName。在这种情况下,可以节省处理器资源:
button.addEventListener('click', () => {
window.open('https://google.com', 'meaningfulName')
})
这样,例如,当你在一个按钮上单击10次时,浏览器将始终在一个新选项卡中重新阅读它,而不是在10个不同的选项卡中打开它,这将消耗更多的资源。
您可以在MDN上阅读有关此的更多信息。
要打开新选项卡并保持在同一位置,可以在新选项卡中打开当前页面,然后将旧选项卡重定向到新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
浏览器将自动将您移动到新打开的选项卡。看起来您的页面已重新加载,您将停留在同一页面上,但在新窗口上:
我将在一定程度上同意下面的人的观点(此处转述):“对于现有网页中的链接,如果新网页与现有网页是同一网站的一部分,浏览器将始终在新选项卡中打开链接。”至少对我来说,这条“通用规则”适用于Chrome、Firefox、Opera、Internet Explorer、Safari、SeaMonkey和Konqueror。
不管怎样,有一种不那么复杂的方法可以利用对方所呈现的内容。假设我们讨论的是您自己的网站(下面的“thisite.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
}