Passing an object from knockout to opener window - javascript

I have the following scenario in my site, a page (opener) can open a "Settings" page, where you can change settings, save and close in order to continue in the opener page.
The problem is that right now the settings aren't passed along from the settings page to the opener page.
So I added this in the saveSettings function:
saveSettings: function () {
var jsonObj = ko.mapping.toJSON(this.ViewModel);
SD.CORP.WS.HedgingEffectivenessSettingsService.SetHedgingEffectivenessSettings(userID, companyID, selectedProductID, jsonObj, saveSettingsOnSucc, saveSettingsOnFaild);
This is an example of what I've added:
var settings = JSON.parse(jsonObj);
window.opener.requestParameters.ReportSetting.ProspectiveTestSettings = settings.ProspectiveTestSettings;
}
But when I try to use it on the opener these objects are empty, if I try to JSON.stringify the object I get a "The interface is unknown" error.
How can I fix this?
EDIT:
I found out in the meanwhile that the actual problem was that I assigned an object from the settings window to the opener window, so when I closed the settings window, the object no longer existed.
I fixed it by adding a function on the opener script so that I can call it from the settings page and then use $.extend in order to create a deep copy on the opener page.

You can try to use window.postMessage to send the settings from the settings window to the opener. Article on how to use: https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
Opener:
window.addEventListner('message', function(event) {
var settings = JSON.parse(event.data)
}, false);
Settings window:
window.postMessage(JSON.stringify(jsonObj));

Related

Return value from PopUp to parent

I have a difficult question and don't know if this is possible:
I have a link on my parent window that opens a popup with a webpage: forum.website.com. This webpage is a page with a forum where an user can post a new topic. He type the subject and the content, and submits the topic. The url is now: forum.website.com?board=1&topic=X where the X is the unique id. Now this ID should be sent to the parent window, so it knows the id of the new generated topic. How can I do this with javascript?
Thanks!
Use sessionStorage for solving this:
http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
Parent / source window code:
var storedData;
function setData(id){
storedData = id;
}
Popup code:
function topicPosted(id){
opener.setData(id);
// Do stuff
}
When you close a popup in IE, the data assigned to the opener's object by the popup is lost. That's why you need to call a function from from the popup to the opener, with the data as parameters. The function then sets (copies) the data to variables in the opener.
If it weren't for IE, you might have simply done this:
function topicPosted(id){
opener.storedData = id;
// Do stuff
}

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).

How pass window handler from one page to another? (JavaScript)

I have a very strange problem , please don’t ask me why do I need this…
I have a page1. Page1 has a link which opens new window (page2) using window.open function.
chatWindow is a handler of child window with returns from window.open function.
Now I'm moving from page1 to page3 (by link Some Text). And I need to check on the page3 if page2 is close or open.
How to pass handler chatWindow from page1 to page3?
Thank you in advance!
On page2 and page3, you can refer to page1 using window.opener. In page1, you can define a method which checks whether page2 is still open or not: window.open returns an instance of the new window, and null if the window has been closed.
Note that you can only read properties from windows if they're at the same domain. If they're from different domains, you can enable communication using the window.postMessage method.
Assuming that they're at the same domain, you can use the following code (concept code):
window.page2 = window.open('...');
window.page3 = window.open('...');
// At page3:
if (window.opener && window.opener.page2 != null) { // Not null or undefined
// Do something
}
I have used global variables for the ease. A better implementation can consist of a namespace:
window.openedWin = {};
window.openedWin.page2 = window.open('...');
...
// At page3:
if (window.opener && window.opener.openedWin && window.opener.openedWin.page2 ...

How can we know when pop-up window url is loaded (window.open)?

I need to change the URL of the page in the pop-up as soon as it completes loading ( I am using window.open function call).
Is there anyway I can find out when the page in pop-up has completed loading in the parent window? I cannot change anything in the page I am opening in pop-up, because it belongs to another website.
window.open returns a reference to that window's window object.
If the opened window is pointing to a URL on the same domain as the window opener, then it will have full access to that object just as it does it's own window object.
var w = window.open(url);
// If the window opened successfully (e.g: not blocked)
if ( w ) {
w.onload = function() {
// Do stuff
};
}
The same origin policy applies here. If the URL of the opened window is on a different domain, then the opener will not have access to members of that window's reference.
this seems pretty self-explanatory, but tell me if you need more explanation (or if it doesn't work, though it should...)
var winObj = window.open( /* lot of params */ );
if( !winObj )
{
/* pop-up blocked! */
}
else
{
winObj.onload = function( ){ /* do stuff here */ };
}

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