I need to pass some JavaScript object to the new window opening. Below code works fine when I open page in new tab.
var url = "http://page1.html";
var win = window.open(url, "_blank");
win.myData = myData;
win.focus();
And I am able to access the data on page1.html using
var data = window.opener.myData;
But if opens the page in same tab using
var win = window.open(url, "_self");
This method not works. I am getting TypeError: Cannot read property 'myData' of null on second page.
How can I pass the data when open the new page in same tab.
As comments suggested you could use a form of persistent storage such as a cookie or localStorage. However these may be blocked/disabled by the user via browser settings.
Passing your data as a query parameter appended to the url would seem the most straightforward and reliable option. There are considerations regarding this method, such as the maximum permissable length of a url; and privacy - urls will be stored in browser history, logged by the ISP etc.
The data will also need to be in a url-safe format. You can use encodeUriComponent for this, perhaps encoding it as a base64 string beforehand to avoid having the plaintext data in the url.
var data = {
thing: 'something here',
otherThing: [{ name: 'zoo', size: 1 }, { name: 'far', size: 9001 }]
};
var dataString = JSON.stringify(data);
var dataStringBase64 = window.btoa(dataString); // (optional)
var dataStringBase64Safe = encodeURIComponent(dataStringBase64);
var url = 'https://example.com?data=' + dataStringBase64Safe;
window.open(url, '_self');
On the new page (grabbing the desired query param, then reversing the steps):
var urlParams = new URLSearchParams(window.location.search); // supported on most modern browsers
var dataStringBase64Safe = urlParams.get('data');
var dataStringBase64 = decodeURIComponent(dataStringBase64Safe);
var dataString = window.atob(dataStringBase64);
var data = JSON.parse(dataString);
console.log(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With