LakshmiNarayana
LakshmiNarayana

Reputation: 63

How to call user function in Mozilla Addon?

Can some one tell me what is wrong with code. Here i want to send POst request to webpage when clicked on Context menu. Post data would be url that is clicked.

var buttons = require('sdk/ui/button/action');
var tabs = require("sdk/tabs");
var cm = require("sdk/context-menu");
var Request = require('sdk/request').Request;
var self = require("sdk/self");


function sendRequest(turl) {
    Request({url: 'myurl.com',content: {data: turl},onComplete: function (response) {console.log(response.text);}}).post();
};

var script = "self.on('click', function (node, data) {" +
             "sendRequest(node);" +
             "});";

cm.Item({
  label: "Save To nbojanapu",
context: cm.SelectorContext("a"),
contentScript: script

});

Upvotes: 1

Views: 92

Answers (1)

humanoid
humanoid

Reputation: 764

The problem here is, that sendRequest is not defined for the contentScript in the context menu. You would have to use the messaging function (https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/context-menu#message)

var script = "self.on('click', function(node, data) {" +
             "  self.postMessage(node.href);" +
             "});";

cm.Item({
  label: "Save to nbojanapu",
  context: cm.SelectorContext("a"),
  contentScript: script,
  onMessage: sendRequest
});

So instead of calling sendRequest directly in the contentScript, it's called in the message event handler (which I attached directly in the constructor of the item). The message is sent from the contentScript using the self.postMessage method, which, by the way, doesn't support making structured clones of an Object, or in other words, if you'd send the whole node with a message it would be broken on the receiving end (see also https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/using_postMessage). Since you seem to just want the href attribute, I just send that directly.

Upvotes: 1

Related Questions