CodeDezk
CodeDezk

Reputation: 1260

Html pass data to new window using javascript

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.

Upvotes: 3

Views: 2164

Answers (2)

Asanka
Asanka

Reputation: 618

What about using Data URLs, with base64 encoded data,

ex:

var string = JSON.stringify({
name: "x",
age: 23
});

// Encode the String
var encodedString = btoa(string);
console.log(encodedString);

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs:  "{"name":"x","age":23}"

this way you can send even a image How to decode data:image/png:base64... to a real image using javascript

Read on Data Urls

Upvotes: 1

FishSaidNo
FishSaidNo

Reputation: 405

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

Upvotes: 1

Related Questions