Reputation: 788
I'm building a bookmarklet for a service. I need to transfer data (url, text) from open window but I don't know which would be the best method. GET limits the amount of data and ajax isn't possible due cross-domain problem.
What would be the optimal way?
Upvotes: 3
Views: 1548
Reputation: 5926
You can put your data in an encoded JSON string and send it with and AJAX POST. AJAX support POST.
Upvotes: 0
Reputation: 76736
You could use POST if it's a lot of data. Create a hidden iframe with a form with a textbox. Set the form method to post and the action to your service. Put the data into the textbox, attach the iframe to the document, and submit the form.
Try something like this:
function postData (data, url, cb) {
var f = document.createElement('iframe'),
fname = (+((''+Math.random()).substring(2))).toString(36);
f.setAttribute('name', fname);
f.setAttribute('id', fname);
f.setAttribute('style', 'width:0;height:0;border:none;margin:none;padding:none;position:absolute;');
document.body.appendChild(f);
var frame = window.frames[fname],
doc = frame.document,
form = doc.createElement('form'),
text = doc.createElement('textarea');
text.setAttribute('name', 'data');
text.appendChild(doc.createTextNode(data));
form.setAttribute('action', url);
form.setAttribute('method', 'post');
form.appendChild(text);
doc.body.appendChild(form);
if (cb) { document.getElementById(fname).onload=cb; }
doc.forms[0].submit();
}
You can remove the iframe from the document in the callback if you want.
Upvotes: 7
Reputation: 316
The method no recommends would work.
An alternate method, to get around the cross-domain issue: you can host a JS file with a majority of the JavaScript required (including the XHR code), and simply use your bookmarklet code to inject a script element into the current page referencing your JS file (line-breaks added for readability; remove them in the bookmarklet code of course):
javascript:(function() {
var sc = document.createElement("SCRIPT");
sc.type = "text/javascript";
sc.src = "http://domain.com/path/to/script.js";
document.body.appendChild(sc);
})();
Upvotes: -1