如何在新窗口中打开链接



我正在尝试使用HTML&JS。

到目前为止,我已经设法做到了<a href="myLink" target="_blank" rel="noreferrer">myText</a>,但这只是使链接在一个新的选项卡中打开

这是如何在新窗口中打开链接。

<a href="myLink" 
target="popup" 
onclick="window.open('myLink','popup','width=600,height=600'); return false;">
Open Link in Popup
</a>

永远记住,有时用户会将浏览器配置为阻止所有新的选项卡和窗口(至少我是这样做的(,以避免烦人的广告和点击诱饵链接。

任何打开新浏览器上下文而不指定维度的方法都将根据用户的偏好使用选项卡或窗口。

总的来说,试图绕过这种偏好不是一个好主意。如果用户决定要在新窗口中使用一个选项卡,他们总是可以将其撕成一个选项卡。

也就是说,如果你指定了尺寸,如果浏览器完全支持,它将触发一个新窗口(例如,大多数移动设备根本不支持窗口(。

addEventListener("click", event => {
const target = event.target;
if (!target.classList.contains("force-window")) {
return;
}
const url = target.href;
const width = window.innerWidth;
const height = window.innerHeight;
const features = `width=${width},height=${height}`;
window.open(url, "_blank", features);
event.preventDefault();
});
<a href="myLink" target="_blank" rel="noreferrer" class="force-window">myText</a>

不幸的是,这将产生一个缺少大多数预期功能的窗口。请参阅window.open文档将其添加回,但请注意(在Chrome中至少(将菜单栏添加回将导致忽略高度和宽度,并将其放回新选项卡中。

作者控制的新窗口是一种痛苦,几乎总是最好避免。除非我需要在一个小窗口中弹出一些内容(比如聊天或音乐播放器(,当用户浏览网站时,这些内容可以保留在屏幕上,否则我不会碰它们……即使这样,我也通常倾向于写SPA。

当您想要打开具有给定url的弹出窗口时,必须使用window.open()函数。

windows.open()接受一些称为Window特性的参数,您可以在这里找到https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Window_features,定义弹出窗口。当你通过一个宽度高度时,它将在弹出窗口中打开。

<a id="url" href="https://www.google.com">myText</a>
<script>
document.getElementById("url").addEventListener('click', evt => {
evt.preventDefault();
let elem = document.getElementById("url");
let url = elem.getAttribute("href");
window.open(url, "popup", "width=700,height=700");
});
</script>

最新更新