简体   繁体   中英

FireFox Extension SDK converting GM_xmlhttprequest to somthing compatible with the addon sdk

I started with a grease monkey script. there you use the command GM_xmlhttprequest and are able to get cross domain data. I originally had the code below working in Greasemonkey, now that i have grown beyond GM capibilitys I need to move it over to the addon SDK.

GM_xmlhttpRequest({
      method: 'POST',
      url: "http://10.1.1.1/app/site_search_info.php",
      headers: {
             "Content-Type": "application/x-www-form-urlencoded"
          },
      data: encodeURI("link=" + itemDir[2]),
      onload:function(r)
               {
               ................ original html formating code here...
               }
 });

I was able to pull the date information about each rows item and then have it append that information behind the current text in each row. i used a pagemod call in main.js to load my search.js which contians this code. when I get a page that should execute the xmlhttprequest it does not show an error in the browsers error console and does not run. putting an alert just before the XHR does appear. Since it is a cross site XHR i can only assume that either i got the syntax wrong when trying to replace GM_xmlhttprequest, or it is being blocked by security settings.

so for cross site requests should i be using

var Request = require("request").Request;
    Request({
      url: "http://10.1.1.1/app/site_search_info.php",
      headers: {
             "Content-Type": "application/x-www-form-urlencoded"
          },
      content: encodeURI("link=" + itemDir[2]),
      onload:function(r)
            {
................ original html formating code here... 
          };
}).post();

Or should I be using somthing like

var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] 
                    .createInstance(Components.interfaces.nsIXMLHttpRequest); 
req.open('PUT',"http://10.1.1.1/app/site_search_info.php", false); /* synchronous! */ 
req.onload = function (r)
         { 
................ original html formating code here... 
          }; 
req.setRequestHeader('Content-Type', application/x-www-form-urlencoded); 
req.send(encodeURI("link=" + itemDir[2]))

I need to post a items name it ends up encoding "link=pliers" and take the time date result that the php page generates, and run it through the formatting code then append the original web page with that data.

Since this is my first XHR in the sdk I need to figure out if it is a syntax error on the XHR or if it is using the wrong type of XHR because security is blocking that.

If both would work then do they have to be put in a specific .js file or called in a specific way?

You should be using the SDK's Request module, the first option. This code should be in main.js, and in your onComplete handler you should send the data to your content script. Here is a working example that does something like this:

// main.js:

let data = require('self').data;

let pm = require("page-mod").PageMod({
    include: /^https:\/\/twitter.com\/.*\/status\/[\d]+$/,
    contentScriptFile: [data.url('jquery-1.7.1.min.js'), data.url('twitter_json.js')],
    onAttach: function(worker) {

        worker.port.on('tweet-loaded', function() {
            let tweet_id = /status\/([\d]+)$/.exec(worker.tab.url).pop();
            if (tweet_id) {
                let twitter_request = require("request").Request({
                    url: 'https://api.twitter.com/statuses/show/' + tweet_id + '.json',
                    onComplete: function(response) {
                        worker.port.emit('got-tweet-json', response.json);
                    }
                }).get();
            }
        });
    }
});


// content script

$(function() {
    // this setTimeout is a dumb hack, it seems we need to wait a bit longer before
    // modifying the page. I blame new twitter.
    window.setTimeout(function() {
        self.port.on('got-tweet-json', function(data) {
            var s_data = JSON.stringify(data, null, '   ');
            $('ul.actions').after('<pre id="json-dump"></pre>');

            $('ul.actions').append('<li><a id="json-link" href="#">View JSON</a></li>');

            $('#json-link').click(function(ev) {
                $('#json-dump').toggle();
                return false;
            });
            $('#json-dump')
                .html(s_data)
                .hide();
        });

        self.port.emit('tweet-loaded', true);


    }, 200);
});

https://builder.addons.mozilla.org/addon/1040966/latest/

Not the window.setTimeout - I think this is necessary in this case because of all the JS that gets executed on load when viewing new twitter. I be it varies in necessity between OS and browsers. :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM