Bookmarklet data transfer method

I am creating a bookmarklet for the service. I need to transfer data (url, text) from an open window, but I don't know what the best method would be. GET limits the amount of data, and ajax is not possible due to a cross-domain problem.

What will be the best way?

+3
source share
3 answers

You can use POST if it has a lot of data. Create a hidden iframe with a form with a text box. Set the form method for publishing and the action for your service. Put the data in the text box, 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.

+7

JSON AJAX POST. AJAX POST.

0

no .

An alternative method to work around the problem between domains: you can place a JS file with most of the necessary JavaScript (including XHR code) and just use the bookmarklet code to enter a script element in the current page that links to your JS file (line breaks are added for readability, of course, delete them in the bookmarklet code):

javascript:(function() {
    var sc = document.createElement("SCRIPT");
    sc.type = "text/javascript";
    sc.src = "http://domain.com/path/to/script.js";
    document.body.appendChild(sc);
})();
-1
source

Source: https://habr.com/ru/post/1756380/


All Articles