I'm trying to make a window popup with my link using HTML & JS.
So far I've managed to get this <a href="myLink" target="_blank" rel="noreferrer">myText</a>
, but this just makes the link open in a new tab.
This is how to open a link in a new window.
<a href="myLink"
target="popup"
onclick="window.open('myLink','popup','width=600,height=600'); return false;">
Open Link in Popup
</a>
Always remember the sometimes that user configures their browsers to block all new tabs and windows (at least this is what I do), to avoid annoying advertisements and click baits links.
Any method which opens a new browser context without specifying the dimensions will use either a tab or a window according to the user's preferences.
In general, it isn't a good idea to try to bypass that preference. If a user decides they want a tab in a new window, they can always tear it off into one.
That said, if you specify dimensions, it will trigger a new window if the browser supports that at all (most mobile devices, for example, don't support windows at all).
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>
Unfortunately, this will produce a window missing most of the expected features. See the window.open
documentation to add them back, but note that (in Chrome at least ) adding the menubar back will cause the height and width to be ignored and put things back in a new tab.
Author controlled new windows are a pain and are almost always best avoided. I wouldn't touch them unless I needed to do something like pop out some content (like a chat or music player) in a small window that could remain on screen while the user navigated the site … and even then I'd generally lean towards writing a SPA instead.
When you want to open a popup with a given url, you have to use the window.open()
function.
The windows.open()
accepts a few parameters called Window features, which you can find here https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Window_features , to define the popup. When you pass it a width and a height it will open in a popup.
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.