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);
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
Related
I can create an object URL like this:
let pixel = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
let data = atob(pixel);
let buffer = new ArrayBuffer(data.length);
let array = new Uint8Array(buffer);
for (var i = 0;i<data.length;i++){
array[i]=data.charCodeAt(i);
}
let blob = new Blob([buffer], {type: 'image/jpeg'});
let url = URL.createObjectURL(blob);
And I can revoke an object URL like this:
URL.revokeObjectURL(url);
But what I would like to do is automatically revoke the URL after one use.
Is there a way to check if an object URL has been accessed?
Thank you in advance.
EDIT:
In this case, I can't just trigger a function when I use the URL. Instead, I would like to be able to check if it has been used even OUTSIDE of the page. An example would be if someone typed the URL into the address bar, this can't call javascript AFAIK.
If you don't have an API to do this, you could use localStorage to track this.
You could have 2 methods,
addUrlStatus - which takes a url as input and checks whether it has been accessed in the past.
updateUrlStatus - which sets the status of a url to true in localStorage once the user has used the url (not sure what action defines this in your code).
So you could do something like,
let pixel = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
let data = atob(pixel);
let buffer = new ArrayBuffer(data.length);
let array = new Uint8Array(buffer);
for (var i = 0;i<data.length;i++){
array[i]=data.charCodeAt(i);
}
let blob = new Blob([buffer], {type: 'image/jpeg'});
let url = URL.createObjectURL(blob);
addUrlStatus(url);
function addUrlStatus(url) {
var _url = localStorage.getItem(url);
if(!_url) {
localStorage.setItem(url, false); // false indicates it hasn't been used yet.
return;
}
}
// this function needs to be called when the user has used the url.
function updateUrlStatus(url) {
localStorage.setItem(url, true);
URL.revokeObjectURL(url);
}
I have to use a XMLHttpRequest, but I don't know which data format is expected by the function request.send(). I searched for too long now.
I tried to pass a JSON object but it does not work:
var request = new XMLHttpRequest();
request.open("GET","fileApi");
var data = {
action: "read",
targetFile: "testFile"
};
request.addEventListener('load', function() {
if (request.status >= 200 && request.status < 300) {
$("#messageOutput").html(request.responseText);
} else {
console.warn(request.statusText, request.responseText);
}
});
request.send(data);
I get updateFile:155 XHR finished loading: GET "http://localhost/cut/public/fileApi".
But no data is received on the server. I made this simple check to approve this:
PHP (server side):
$action = filter_input(INPUT_GET, "action");
$targetFile = filter_input(INPUT_GET, "targetFile");
echo ("action = '$action' | targetFile = '$targetFile'");
exit();
Returns: action = '' | targetFile = ''
Unfortunatelly I can't use jQuery in my application, since the target is a C# Webbrowser (Internet Explorer) and it detects errors in the jQuery file and stops my scripts from working...
I don't know which data format is expected by the function request.send()
It can take a variety of formats. A string or a FormData object is most common. It will, in part, depend on what the server is expecting.
I tried to pass a JSON object
That's a JavaScript object, not a JSON object.
request.open("GET","fileApi");
You are making a GET request. GET requests should not have a request body, so you shouldn't pass any data to send() at all.
GET requests expect data to be encoded in the query string of the URL.
var data = {
action: "read",
targetFile: "testFile"
};
var searchParams = new URLSearchParams();
Object.keys(data).forEach((key) => searchParams.set(key, data[key]));
var url = "fileApi?" + searchParams;
console.log(url);
// and then…
// request.open("GET", url);
// request.send();
Warning: URLSearchParams is new and has limited browser support. Finding a library to generate a query string is left as a (simple) exercise to any reader who wants compatibility with older browsers.
Is it possible to store xhr.response in local-storage , code : var xhr = new XMLHttpRequest();xhr.open('GET', 'http://cdn.dmsapp.tk/'+appUrl+'/'+evt+'?authToken='+this.getuserservice.authorizationfun()+'&force=false');localStorage['tifPdfFileObj'] = JSON.stringify(xhr.response);xhr.responseType = 'arraybuffer';xhr.onload = function (e) { localStorage['tifPdfFileObj'] = JSON.stringify(xhr.response);}
I need to store the xhr.response object in local-storage or some where, to use it whenever i want instead of hit api for same image.when i try to stringify the response, it returns empty({}).How to store in local storage and use it.
current usage : var buffer = xhr.response;var tiff = new Tiff({buffer: buffer});
i have another novice (and probably stupid) question. i am using HttpClientRequest and making a post call. also i have the response.
var url = <my url>
var request = new HttpClientRequest(url);
request.header["Content-Type"] = "application/x-www-form-urlencoded";
request.method = "POST";
try
{
request.execute();
var rawResponse = request.response.body.toString();
}
the response from server is in the following format:
{"token":"abc","expires_in":9292,"refresh":"deeDfTTgendj"}
i just need to extract "expires_in" and "refresh" fields from the response
Since that is valid JSON, you can parse it:
var rawResponse = request.response.body.toString(),
objectLiteral = JSON.parse(rawResponse);
var expires_in = objectLiteral['expires_in'],
refresh = objectLiteral['refresh'];
var rawResponse = '{"token":"abc","expires_in":9292,"refresh":"deeDfTTgendj"}';
objectLiteral = JSON.parse(rawResponse);
var expires_in = objectLiteral['expires_in'],
refresh = objectLiteral['refresh'];
console.log(expires_in, refresh);
Note: check out browser support for JSON.parse()
I'm working in a little web app that generates an base64 image, I'm using blob to put it back into a file (is a .png but I haven't renamed it yet), now I'm trying to save it on my sever Any ideas or different approaches?
This is the script:
var img = document.getElementById("MyPix");
img.onclick = function() {
var image_data = atob(img.src.split(',')[1]);
var arraybuffer = new ArrayBuffer(image_data.length);
var view = new Uint8Array(arraybuffer);
for (var i=0; i<image_data.length; i++) {
view[i] = image_data.charCodeAt(i) & 0xff;
}
try {
var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
} catch (e) {
var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
bb.append(arraybuffer);
var blob = bb.getBlob('application/octet-stream');
}
var url = (window.webkitURL || window.URL).createObjectURL(blob);
valor = (document.getElementById("link").value = url)
location.href = valor;
};
I'm not very good with js so if you want to have a better idea visit the project clicking here its all javascript so just see source code.
you can't save to your server with just client-side JavaScript. Form the data you want to save in Javascript, then POST that to your server with a call to a page that you write that can turn POST data into a file on your filesystem, so in your case a .php file with code that looks for $_POST data and then writes that to file. After making sure it's safe, because anyone will be able to post data to that page, not just people using your webpage.