Reputation: 715
I want to pass an object from one window to another, what if its a complex object, it is possible to write it to cookie somehow? or only opening an saving a link to another window?
var link = window.open('url');
link.myVar = myObj;
or
document.cookie.set('someVar', myObj);
and in the other window:
document.cookie.get('someVar');
Upvotes: 0
Views: 47
Reputation: 1074266
I want to pass an object from one window to another
You're on the right track with your code, but you're trying to give the window a reference to the object too soon. You could wait for it to load:
var link = window.open('url');
link.onload = function() {
link.myVar = myOb;
};
The load
event happens fairly late in the process, though, so I'd probably have the window that's being opened request the object as soon as it can:
// In the window being opened:
var myVar = opener.obj;
Rather than using the variable directly, I'd probably use a function to encapsulate that:
// In the window being opened:
var myVar = opener.getObject();
All of that will only work for windows in the same origin, which I assume they are if you're thinking about cookies. You can also use cross-window messaging if the windows aren't in the same origin.
Just for completeness:
Is possible to write an object to browser cookie?
Cookies can only contain strings. You can serialize your object using JSON.stringify
or similar, but I wouldn't use cookies for cross-window messaging.
Upvotes: 1
Reputation: 943537
Cookies can only hold strings. They are designed to be transmitted in HTTP headers.
You can pass more complex data structures by encoding them as strings (e.g. with JSON.stringify
), but a reference to another window is out of the question.
Upvotes: 1