codecowboy
codecowboy

Reputation: 10095

How can I use a page's jQuery methods from a mozilla add-on?

I would like to make this happen on a loaded page when a user clicks an add-on widget:

var e = jQuery.Event("keydown", { keyCode: 405 }); 
$("input").trigger(e);

jQuery is already loaded in the target page. I've tried this:

var widgets = require("widget");
var tabs = require("tabs");
var pageMod = require("page-mod");

var widget = widgets.Widget({
    id: "button-test",
    label: "button-test",
    contentURL: "http://www.mozilla.org/favicon.ico",
    onClick: function() {
        tabs.activeTab.attach({
            contentScript:
                'var e = window.jQuery.Event("keydown", { keyCode: 405 }); $("input").trigger(e);'
        });
    }
});

I get the following error in the console:

Timestamp: 30/08/2012 14:06:36
Error: An exception occurred.
Traceback (most recent call last):
  File "javascript:var e = window.jQuery.Event("keydown", { keyCode: 405 }); $("input").trigger(e);", line 1, in 
TypeError: window.jQuery is undefined

Do I need postMessage or port.emit()? I;ve also tried just jQuery.event (without the window)

Upvotes: 2

Views: 935

Answers (2)

codecowboy
codecowboy

Reputation: 10095

This is what worked for me:

var widgets = require("widget");
var tabs = require("tabs");
var data = require("self").data;

var widget = widgets.Widget({
    id: "div-show",
    label: "Show divs",
    contentURL: "http://www.mozilla.org/favicon.ico",
    onClick: function() {
        tabs.activeTab.attach({
            contentScriptFile:
                [data.url("jquery-1.8.0.min.js")],
            contentScript: [
                "$(window).keydown(function(e){ \
                console.log(e.keyCode);}); $(window).trigger(jQuery.Event('keydown', { keyCode: 405 })) "]

        });
    }
});

Clicking on the widget icon generates a keydown event which then gets logged

Upvotes: 0

Wladimir Palant
Wladimir Palant

Reputation: 57651

jQuery is already loaded in the target page.

Yes, and the webpage can access it. However, your content script doesn't have direct access to the webpage, for security reasons. You could access jQuery (and other JavaScript variables defined by the page) as unsafeWindow.jQuery but this has serious security implications - not recommended to use. In your case it would be better to add your own copy of jQuery to your extension and load it with your content script - then you can be sure that jQuery is there and does exactly what you expect it to do:

var {data} = require("self");
tabs.activeTab.attach({
    contentScriptFile: [data.url("jquery.js"), data.url("contentScript.js")]
});

Upvotes: 1

Related Questions