I am converting a page that uses multiple "alert" popups to use secondary windows so I can control the size and location and so the css will will work. What happens is that window.open() third parameter contains the position and size of the popup.
The size part works as expected BUT the "top=" and "left=" can be anything and the new window will always open in the upper left corner of the terminal screen, not in the browser window.
Some of the other values work but some don’t; eg the location bar always appears even when it is set to "location=no"
I have reviewed many similar questions but none of the answers seem relevant.
In trying to eliminate things like parent markup as the culprit I created a minimalist function that will always open in the upper left corner about 1/2" in from the edge of the terminal screen:
<!DOCTYPE html>
<head>
<script type="text/javascript" "language=javascript">
var popwin = null;
function newwin() {
popwin = window.open("", "", "top=500,left=2000,height=600,width=400,titlebar=no,scrollbar=yes,location=no,popup=yes");
popwin.document.write("XXXXX");
console.log("top=" + window.screenY + ", left=" + window.screenX);
}
</script>
</head>
<body>
<center>
<p>test page for popup window</p>
</center>
<br /> <br />
<center><button onClick="newwin()">Click to open window</button></center>
<br /> <br />
</body>
</html>
The console log shows top=23 left=26 which is pretty much what I see. I need to be able to open the window over the existing primary window in the application so the old/new data can be compared.
The document.write function is only there to prove that this is the window that I am actually seeing on the screen.
2
Answers
There are a number of issues here. First, of all, the values you use in your example (
top=500,left=2000,height=600,width=400
) are likely to put at least part of the window off screen. This will be automatically corrected by the browser. As MDN notes:Secondly, in the code where you are checking the position, you’re actually reporting the main window’s position, not the popup’s. Instead of:
That should be:
This example correctly positions and reports the position of a popup window:
Lastly, concerning the address bar: it is in most modern browsers no longer possible to open a popup window without displaying the address bar, for security reasons. See more info in this answer.
In conclusion, there are better alternatives than using popups. They annoy users, and are routinely blocked by browsers. Depending on your use case, you could use something like a
dialog
element.Try this code:
This will correctly adjust the position of the new window