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