We are use window.open for open popup. But then we want find it and close. Unfortunately we can`t save this popup handle to variable.
P.S. How get list of all windows?
This should work:
var wh = window.open(..)
wh is the handle to the popup window.
If you have control over the page that loads the script, you could do something like this. Warning: this is a really scary and generally bad thing to do:
<script>
var windowHandles = {};
(function() {
var realOpen = window.open;
window.open = function(url, name, features) {
windowHandles[name] = realOpen(url, name, features);
};
})();
</script>
That will build an object (windowHandles) in which the handles for each opened window will be saved.
Put that script in your page before the script that opens the other window is loaded.
I found not perfect solution, but it work.
win = window.open(null, 'Window1');
This code search search window with this name and return handler, but if window is closed it open empty popup.
I Think this is temporary solution
I don't like this solution. Fixing the script to give you a handle would be a better bet.
<button onclick="go()">Go</button>
<button onclick="stop()">Stop</button>
<script type="text/javascript">
function go() {
// Existing function. It opens a window with a name.
window.open('http://google.com', 'test', 'width=300,height=300');
}
var foo;
function stop() {
// Open a new window with the same name. It replaces the existing window.
// Since it opens a local document, the Same Origin Policy does not apply.
// ... and we can capture its return value to grab a handle on an existing
// window
foo = window.open('black-local-page.html', 'test', 'width=300,height=300');
// Give the local page time to load
setTimeout(continue_stopping, 500);
}
function continue_stopping() {
// Call window.open() on the window
foo.close();
}
</script>
Related
I have a button in my homepage that opens to a new window FindAPark.html. I'm trying to pass a variable to that HTML page without GET.
I've tried this in my Homepage.js:
function buttonClick() {
var newWindow = window.open('FindAPark.html');
newWindow.my_special_setting = "Hello World";
}
And then in my FindAPark.js:
window.my_special_setting;
console.log(window.my_special_setting);
The console says it's "undefined" instead of showing "Hello World". What might be the problem, and what might fix it?
EDIT: Now it's telling me "Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame." I haven't hosted these on a domain yet, but I own both HTML files. What do I do?
Use window.postmessage
In the opened window
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
console.log(event)
// ...
}
Now dispatch the event from the parent window
newwindow.postMessage("The user is 'bob' and the password is 'secret'",
"https://secure.example.net");
Use localStorage like this:
function buttonClick() {
localStorage.setItem("mySepcialSetting", "Hello World");
window.location.href = "FindApark.html";
}
Then you can access it as follows:
var mySpecialSetting = localStorage.getItem("mySepcialSetting");
console.log(mySpcialSetting);
Provided your opened window is from the same security domain, you can pass the variable like you did in your question, but you should wait for the new window to completely load.
let newWindow = window.open('FindAPark.html');
newWindow.addEventListener('load', function(){
newWindow.my_special_setting = "Hello World";
}, false);
Another option is to read a variable from the window that opens the new window... same security policies apply as above.
let my_special_setting = window.opener.my_special_setting;
For a script I'm writing, I'd like to use the native window.open method. However, a script already loaded to which I don't have access, overwrites the global window.open method with a boolean (ouch).
I know how to restore the methods on the Document (via HTMLDocument.prototype), but I don't know how to restore them on the Window, as I can't seem to find the equivalent for that to Window. Window.prototype.open does not exist for example.
I have tried creating an iframe, and getting the open method from that contentWindow in the iframe, but the browser will block opening windows using open because it was probably created in another origin. Neither delete open; does work because open was defined using var in the globally loaded script.
So, how can I restore the open method, defined as 'native code' in Chrome?
I know there are similar questions around, but actually the main question is:
Is there a equivalent of HTMLDocument for the Window object?
I've found this question and the accepted answer (using an iframe) could be used in your case.
The only issue is you can only use the retrieved version of window.open as long as the iframe is still in your document.
function customOpen() {
// local variables definitions :
var url = "https://stackoverflow.com", iframe, _window;
// creating an iframe and getting its version of window.open :
iframe = document.createElement("iframe");
document.documentElement.appendChild(iframe);
_window = iframe.contentWindow;
// storing it in our window object
window.nativeOpen = _window.open;
try {
window.open(url);
} catch (e) {
console.warn(e); // checking that window.open is still broken
}
window.nativeOpen(url);
// deleting the iframe :
document.documentElement.removeChild(iframe);
}
document.getElementById("button").addEventListener("click", customOpen);
Another JSFiddle
Keeping the workaround answer in case someone needs it :
Can you execute a custom script prior to the execution of the script that redefines window.open? If so, you could create a copy of the window.open in another global variable.
It could look like this :
1. First : a backup script
window.nativeOpen = window.open;
2. Then, whatever the window.open overwriting script does :
window.open = false; // who does that, seriously?
3. Your window opening script, that'll use your window.open copy :
function customOpen() {
var url = "https://stackoverflow.com";
try {
window.open(url);
} catch (e) {
console.warn(e);
}
window.nativeOpen(url);
}
JSFiddle example
If I add this code between a <script> and a </script>:
function test()
{
var newWindow = window.open("https://stackoverflow.com/", "a", "width = 600,height = 400");
document.write(newWindow.location.href);
document.write(newWindow.innerWidth);
}
test();
And the output is "about:blank" and 0, though I think it should be "https://stackoverflow.com/" and 600.
I am so confused about this and waiting for a explanation.
AND: if I do want to get the URL of the new window, how should I do?
MANY THANKS.
You can capture these values asynchronously if you wait on the load event:
var newWindow = window.open('http://www.stackoverflow.com', 'a', 'width=600,height=400')
newWindow.addEventListener('load', function () {
console.log(newWindow.location.href);
console.log(newWindow.innerWidth);
});
However, as James Thorpe points out, this will only work if the new window is in the same domain as the page where the script is running, and this happens asynchronously, so whatever you're trying to accomplish by using document.write() might not work.
I have a html page. In the body of the page I am calling onload event which calls javascript function to open a pop up window. here is the code:
var newWindow = null;
function launchApplication()
{
if ((newWindow == null) || (newWindow.closed))
{
newWindow = window.open('abc.html','','height=960px,width=940px');
}
}
when I move to another page, and come back to that page again, popup reopens, although it is already opened. Please guide me to proper direction so that if pop up is already open then it should not open again. I tried document.referred but it requires the site online, currently I am working offline.
newWindow = window.open('abc.html','com_MyDomain_myWindowForThisPurpose','height=960px,width=940px');
Give the window a name. Basing the name on your domain like this, prevents the chances of you picking a name someone else happened to choose.
Never make up a name that begins with _, those are reserved for special names the browser treats differently (same as with the "target" attribute of anchor elements).
Note that if the window of that name was opened with different options (e.g. different height), then it'll keep those options. The options here will only take effect if there is no window of that name, so you do create a new one.
Edit:
Note that the "name" is of the window, not of the content. It doesn't affect the title (newWindow.document.title will affect that, as of course will code in abc.html). It does affect other attempts to do stuff across windows. Hence another window.open with the same name will reuse this window. Also a link like clicky! will re-use it. Normal caveats about browsers resisting window-opening in various scenarios (popup-blocking) apply.
To open a window and keep a reference to it between page refresh.
var winref = window.open('', 'MyWindowName', '');
if(winref.location.href === 'about:blank'){
winref.location.href = 'http://example.com';
}
or in function format
function openOnce(url, target){
// open a blank "target" window
// or get the reference to the existing "target" window
var winref = window.open('', target, '');
// if the "target" window was just opened, change its url
if(winref.location.href === 'about:blank'){
winref.location.href = url;
}
return winref;
}
openOnce('http://example.com', 'MyWindowName');
You can check if the window is open or closed by re-assigning a reference to it when it closes. Example:
var newWindow;
var openWindow = function(){
newWindow = newWindow || window.open('newpage.html');
newWindow.focus();
newWindow.onbeforeunload = function(){
newWindow = null;
};
};
Use the "closed" property: if a window has been closed its closed property will be true.
https://developer.mozilla.org/en-US/docs/Web/API/Window/closed
When you move on another page (on the same domain), you can re-set the window.open variable with popup page like this :
https://jsfiddle.net/u5w9v4gf/
Step to try :
Click on Run (on jsfiddle editor).
Click on Try me (on preview).
Click on Run to move on another page, the variable will be re-set.
Code :
window.currentChild = false;
$("#tryme").click(function() {
if (currentChild) currentChild.close();
const child = window.open("about:blank", "lmao", 'width=250,height=300');
currentChild = child;
//Scrope script in child windows
child.frames.eval(`
setInterval(function () {
if (!window.opener.currentChild)
window.opener.currentChild = window;
}, 500);
`);
});
setInterval(function() {
console.log(currentChild)
if (!currentChild || (currentChild && currentChild.closed))
$("p").text("No popup/child. :(")
else
$("p").text("Child detected !")
}, 500);
I'm creating a Safari Extension. At one point, I want to open a new tab/window and enter text on some text fields in that new tab.
This is what I tried.
var newWindow = window.open('http://openradar.appspot.com/myradars/add', "new tab");
var fillContent = function () {
//Fill some content
//This never get called
};
newWindow.onload = fillContent;
The problem is that the function never get called.
During debugging, I saw that newWindow is valid but that newWindow.onload is always undefined, before and after newWindow.onload = fillContent;
Is it possible to do what I'm trying to do? Is there a better way?
If the page you are trying to open is in another domain, it's impossible, because you were violating javascript's same origin policy (which states that you can only 'control' pages that are on the same domain where the script is running).