Javascript object accessible from all browser windows? - javascript

is it possible to access a javascript object from all browser windows?
is there a global object to store data in?
for example: we want to put information in one window from multiple opened or later opened windows.
Thank you

As long as one window is opened from another, and they open pages in the same domain, they can access each other. If you use the window.open method, you get a reference to the window object of the new window, and the window.opener property in the new window points to the window from where it was opened.
If you open a new instance of the browser, then the windows are completely separate and there is no way for the client scripts to communicate directly. Even if you open the page in a new window in the same instance, they can't communicate because they are not aware of each other.

You can pass the information to the target window via window.open , „javascript:“ using target and even initialize it, if it do not exists.
For example:
You have a page “mypage.html” and there a javascript object myObject, and want to pass from any window in the browser the information foo = 'hello'.
mypage.html :
....
var myObject = {
qs = {},
init: function()
var b = window.location.href.split("?");
if(b.length > 1){
var p = b[1].split("&");
for(var i = 0; i < p.length; i++){
var c = p[i].split("=");
qs[c[0]] = c[1];
}
}
this.doFoo();
},
doFoo: function(){
var foo = this.qs.foo;
....
}
...
};
myObject.init();
...
the calling html's:
window.open(
'javascript:if(typeof(myObject) == "undefined"){'
+ 'setTimeout(\'window.location.href = "mypage.html?foo=hello"\', 10);}'
+ 'else{myObject.qs={}; myObject.qs.foo="hello"; myObject.doFoo();}'
, "mypage"
);
the setTimeout is only needed for chrom, because he got the "window.location.href" property not at startup.

If you are targeting modern browsers, you can use HTML 5 storage.
http://www.quirksmode.org/blog/archives/2009/06/html5_storage_t.html
and as #Guffa said, you can have communication between parent window and child window
easily even without storage.

Related

Popup window accessing parent dom

I have a popup window that needs to access the parent dom to generate a print page. The structure of the print page is significantly different then the structure of the parent so a print css would not solve the problem. I basically want to popup a window and then have that window grab some data from the parent of even access the dom from the popup and generate the print page without having to go to the server again. Any ideas how i can achieve this?
Im using the standard
window.open()
to pop up a window. I need this solution to not be a hack and be cross browser compatible with all major browsers.
Thanks in advance!
Sajjan's answer is a start, but better make sure your objects are available before you try to access them:
var opener = window.opener;
if(opener) {
var oDom = opener.document;
var elem = oDom.getElementById("your element");
if (elem) {
var val = elem.value;
}
}
Otherwise, you do run the risk that the opener doesn't respond to your initial call, and that you can't get the element from it.
As jQuery, I think (based on an answer, here: how to access parent window object using jquery?):
var opener = window.opener;
if(opener) {
var elem = opener.$("#elementId");
if (elem) {
var val = elem.val(); // I forgot we're dealing with a jQuery obj at this point
}
}
window.opener.document.getElementById("your element").value
According to MDN, window.open() will return you a handle to the new window.
var popUpHandle = window.open();
With this handle you should be able to access the DOM of the PopUp. It is possible vice-versa using the already mentioned window.opener. Refer again to MDN:
var originalWindow = window.opener;
Still, your favorite search engine will provide you more details, as this is topic is fairly old and your approach has already been done a million times or more.
parent.document helped in my case.
var elem = parent.document.getElementById("overlay_modal");
if (elem) {
alert('setting attribute');
elem.setAttribute("onclick", "Windows.close('2', event);");
}

Pass argument array to window.open like window.showModalDialog [duplicate]

I have a page which spawns a popup browser window. I have a JavaScript variable in the parent browser window and I would like to pass it to the popped-up browser window.
Is there a way to do this? I know this can be done across frames in the same browser window but I'm not sure if it can be done across browser windows.
Putting code to the matter, you can do this from the parent window:
var thisIsAnObject = {foo:'bar'};
var w = window.open("http://example.com");
w.myVariable = thisIsAnObject;
or this from the new window:
var myVariable = window.opener.thisIsAnObject;
I prefer the latter, because you will probably need to wait for the new page to load anyway, so that you can access its elements, or whatever you want.
Provided the windows are from the same security domain, and you have a reference to the other window, yes.
Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to the window which created it.
Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.
Yes, scripts can access properties of other windows in the same domain that they have a handle on (typically gained through window.open/opener and window.frames/parent). It is usually more manageable to call functions defined on the other window rather than fiddle with variables directly.
However, windows can die or move on, and browsers deal with it differently when they do. Check that a window (a) is still open (!window.closed) and (b) has the function you expect available, before you try to call it.
Simple values like strings are fine, but generally it isn't a good idea to pass complex objects such as functions, DOM elements and closures between windows. If a child window stores an object from its opener, then the opener closes, that object can become 'dead' (in some browsers such as IE), or cause a memory leak. Weird errors can ensue.
Passing variables between the windows (if your windows are on the same domain) can be easily done via:
Cookies
localStorage. Just make sure your browser supports localStorage, and do the variable maintenance right (add/delete/remove) to keep localStorage clean.
One can pass a message from the 'parent' window to the 'child' window:
in the 'parent window' open the child
var win = window.open(<window.location.href>, '_blank');
setTimeout(function(){
win.postMessage(SRFBfromEBNF,"*")
},1000);
win.focus();
the to be replaced according to the context
In the 'child'
window.addEventListener('message', function(event) {
if(event.srcElement.location.href==window.location.href){
/* do what you want with event.data */
}
});
The if test must be changed according to the context
In your parent window:
var yourValue = 'something';
window.open('/childwindow.html?yourKey=' + yourValue);
Then in childwindow.html:
var query = location.search.substring(1);
var parameters = {};
var keyValues = query.split(/&/);
for (var keyValue in keyValues) {
var keyValuePairs = keyValue.split(/=/);
var key = keyValuePairs[0];
var value = keyValuePairs[1];
parameters[key] = value;
}
alert(parameters['yourKey']);
There is potentially a lot of error checking you should be doing in the parsing of your key/value pairs but I'm not including it here. Maybe someone can provide a more inclusive Javascript query string parsing routine in a later answer.
You can pass variables, and reference to things in the parent window quite easily:
// open an empty sample window:
var win = open("");
win.document.write("<html><body><head></head><input value='Trigger handler in other window!' type='button' id='button'></input></body></html>");
// attach to button in target window, and use a handler in this one:
var button = win.document.getElementById('button');
button.onclick = function() {
alert("I'm in the first frame!");
}
Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".
For me the following doesn't work
var A = {foo:'bar'};
var w = window.open("http://example.com");
w.B = A;
// in new window
var B = window.opener.B;
But this works(note the variable name)
var B = {foo:'bar'};
var w = window.open("http://example.com");
w.B = B;
// in new window
var B = window.opener.B;
Also var B should be global.
Alternatively, you can add it to the URL and let the scripting language (PHP, Perl, ASP, Python, Ruby, whatever) handle it on the other side. Something like:
var x = 10;
window.open('mypage.php?x='+x);
I have struggled to successfully pass arguments to the newly opened window.
Here is what I came up with :
function openWindow(path, callback /* , arg1 , arg2, ... */){
var args = Array.prototype.slice.call(arguments, 2); // retrieve the arguments
var w = window.open(path); // open the new window
w.addEventListener('load', afterLoadWindow.bind(w, args), false); // listen to the new window's load event
function afterLoadWindow(/* [arg1,arg2,...], loadEvent */){
callback.apply(this, arguments[0]); // execute the callbacks, passing the initial arguments (arguments[1] contains the load event)
}
}
Example call:
openWindow("/contact",function(firstname, lastname){
this.alert("Hello "+firstname+" "+lastname);
}, "John", "Doe");
Live example
http://jsfiddle.net/rj6o0jzw/1/
You can use window.name as a data transport between windows - and it works cross domain as well. Not officially supported, but from my understanding, actually works very well cross browser.
More info here on this Stackoverflow Post
Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.
I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.
The window.open() function will also allow this if you have a reference to the window created, provided it is on the same domain.
If the variable is used server side you should be using a $_SESSION variable (assuming you are using PHP).

using eval.call() in firefox XPCOM component

I'm making an extension that on load of every page creates an instance of my xpcom component specifically for that page.
I do that like this:
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent) {
appcontent.addEventListener("load", onPageLoad, true);
}
var onPageLoad = function(aEvent) {
var doc = aEvent.originalTarget; //this is the reference to the opened page
pages.push(createInstanceOfMyXPCOM(doc));
}
My question is, within the XPCOM component, how can I use eval() within the global context of that doc. If you would just do this in a regular javascript in html you could do:
window.eval.call(window, somecode);
The problem is I don't have window variable in my xpcom component (or do I), I only have the reference to the document. I could pass the window to my XPCOM component on creation as well, but if I have several pages opened, I don't see how that would work..
From the XPCOM you should be able to get a reference to the main window using:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
Then you can get the currently selected tab document with:
document = mainWindow.gBrowser.contentDocument;
You can fin more information here:
https://developer.mozilla.org/en/Code_snippets/Tabbed_browser
https://developer.mozilla.org/en/Working_with_windows_in_chrome_code
UPDATE:
Try this one, you should be able to get a reference to the most recent window:
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var recentWindow = wm.getMostRecentWindow("navigator:browser");
If you have multiple tabs, you use something like this (code from Mozilla Dev Site) to iterate over all of them and access each document:
var num = gBrowser.browsers.length;
for (var i = 0; i < num; i++) {
var b = gBrowser.getBrowserAtIndex(i);
try {
dump(b.currentURI.spec); // dump URLs of all open tabs to console
} catch(e) {
Components.utils.reportError(e);
}
}

How to Communicate between two browser windows?

I have parent browser window P . on clicking a button a new browser window WIN-A is opened.
then again pressing the same button it should read the title of the WIN-A window and open WIN-B
how to achieve this using Javascript?
Thanks in advance
Given:
var myWindow = open("foo.bar");
Old method: Change the window object's name property:
myWindow.name = "...";
// in foo.bar:
setInterval(someFunctionToCheckForChangesInName, 100);
HTML5 method: Call the window object's postMessage method:
myWindow.postMessage("...", "*");
// in foo.bar:
(window.addEventListener || window.attachEvent)(
(window.attachEvent && "on" || "") + "message", function (evt) {
var data = evt.data; // this is the data sent to the window
// do stuff with data
},
false);
A similar question was just asked recently:
Stack Overflow question: Quickest way to pass data to a popup window I created using window.open()?
Using that as a base (and provided Parent and WIN-A are on the same domain):
// Put outside click handler
var winA = null;
// Put inside click handler
if(!winA){
// Store the return of the `open` command in a variable
var winA = window.open('http://www.mydomain.com/page1');
} else {
var title = winA.document.title;
// Do something with title
var winB = window.open('http://www.mydomain.com/page2');
}
When you call window.open, it returns a reference to the newly opened window. You can store the references to the windows you open in an array, and then iterate that array when you need to open another new window.
Gabriel

Can I pass a JavaScript variable to another browser window?

I have a page which spawns a popup browser window. I have a JavaScript variable in the parent browser window and I would like to pass it to the popped-up browser window.
Is there a way to do this? I know this can be done across frames in the same browser window but I'm not sure if it can be done across browser windows.
Putting code to the matter, you can do this from the parent window:
var thisIsAnObject = {foo:'bar'};
var w = window.open("http://example.com");
w.myVariable = thisIsAnObject;
or this from the new window:
var myVariable = window.opener.thisIsAnObject;
I prefer the latter, because you will probably need to wait for the new page to load anyway, so that you can access its elements, or whatever you want.
Provided the windows are from the same security domain, and you have a reference to the other window, yes.
Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to the window which created it.
Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.
Yes, scripts can access properties of other windows in the same domain that they have a handle on (typically gained through window.open/opener and window.frames/parent). It is usually more manageable to call functions defined on the other window rather than fiddle with variables directly.
However, windows can die or move on, and browsers deal with it differently when they do. Check that a window (a) is still open (!window.closed) and (b) has the function you expect available, before you try to call it.
Simple values like strings are fine, but generally it isn't a good idea to pass complex objects such as functions, DOM elements and closures between windows. If a child window stores an object from its opener, then the opener closes, that object can become 'dead' (in some browsers such as IE), or cause a memory leak. Weird errors can ensue.
Passing variables between the windows (if your windows are on the same domain) can be easily done via:
Cookies
localStorage. Just make sure your browser supports localStorage, and do the variable maintenance right (add/delete/remove) to keep localStorage clean.
One can pass a message from the 'parent' window to the 'child' window:
in the 'parent window' open the child
var win = window.open(<window.location.href>, '_blank');
setTimeout(function(){
win.postMessage(SRFBfromEBNF,"*")
},1000);
win.focus();
the to be replaced according to the context
In the 'child'
window.addEventListener('message', function(event) {
if(event.srcElement.location.href==window.location.href){
/* do what you want with event.data */
}
});
The if test must be changed according to the context
In your parent window:
var yourValue = 'something';
window.open('/childwindow.html?yourKey=' + yourValue);
Then in childwindow.html:
var query = location.search.substring(1);
var parameters = {};
var keyValues = query.split(/&/);
for (var keyValue in keyValues) {
var keyValuePairs = keyValue.split(/=/);
var key = keyValuePairs[0];
var value = keyValuePairs[1];
parameters[key] = value;
}
alert(parameters['yourKey']);
There is potentially a lot of error checking you should be doing in the parsing of your key/value pairs but I'm not including it here. Maybe someone can provide a more inclusive Javascript query string parsing routine in a later answer.
You can pass variables, and reference to things in the parent window quite easily:
// open an empty sample window:
var win = open("");
win.document.write("<html><body><head></head><input value='Trigger handler in other window!' type='button' id='button'></input></body></html>");
// attach to button in target window, and use a handler in this one:
var button = win.document.getElementById('button');
button.onclick = function() {
alert("I'm in the first frame!");
}
Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".
For me the following doesn't work
var A = {foo:'bar'};
var w = window.open("http://example.com");
w.B = A;
// in new window
var B = window.opener.B;
But this works(note the variable name)
var B = {foo:'bar'};
var w = window.open("http://example.com");
w.B = B;
// in new window
var B = window.opener.B;
Also var B should be global.
Alternatively, you can add it to the URL and let the scripting language (PHP, Perl, ASP, Python, Ruby, whatever) handle it on the other side. Something like:
var x = 10;
window.open('mypage.php?x='+x);
I have struggled to successfully pass arguments to the newly opened window.
Here is what I came up with :
function openWindow(path, callback /* , arg1 , arg2, ... */){
var args = Array.prototype.slice.call(arguments, 2); // retrieve the arguments
var w = window.open(path); // open the new window
w.addEventListener('load', afterLoadWindow.bind(w, args), false); // listen to the new window's load event
function afterLoadWindow(/* [arg1,arg2,...], loadEvent */){
callback.apply(this, arguments[0]); // execute the callbacks, passing the initial arguments (arguments[1] contains the load event)
}
}
Example call:
openWindow("/contact",function(firstname, lastname){
this.alert("Hello "+firstname+" "+lastname);
}, "John", "Doe");
Live example
http://jsfiddle.net/rj6o0jzw/1/
You can use window.name as a data transport between windows - and it works cross domain as well. Not officially supported, but from my understanding, actually works very well cross browser.
More info here on this Stackoverflow Post
Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.
I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.
The window.open() function will also allow this if you have a reference to the window created, provided it is on the same domain.
If the variable is used server side you should be using a $_SESSION variable (assuming you are using PHP).

Categories