user3546897
user3546897

Reputation: 41

Firefox addon SDK inject jquery

The script in $(document).ready(...) doesn't work, any ideas why ? It seems the script I try to inject is loaded in the end.

Here my code:

main.js

pageMod.PageMod({
    include: "*",
    contentScriptWhen: 'start',
    contentScriptFile: data.url('inject.js')
});

inject.js

var script = document.createElement('script');
script.src = "resource://directoryOfMyAddon/data/jquery/jquery-1.11.0.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

test.html

<html>
<head>
</head>
<body>
<div id="helloworld"></div>
<script type="text/javascript">
    $(document).ready(function(){
        $("#helloworld").text("Hello, world!");
    });
</script>
</body>
</html>

Thanks O=)

Upvotes: 3

Views: 1370

Answers (2)

nmaier
nmaier

Reputation: 33192

You can inject jquery using the technique you describe, but depending on the contentScriptWhen setting in your page-mod options you won't see the .ready() as the content script will be attached only when after load (contentScriptWhen="end" (default)) or DOMContentLoaded (contentScriptWhen="ready").

You could use contentScriptWhen="start", but at that point there likely isn't a node yet where you could append your <script> tag to.

However, I should mention that it is strongly discouraged (read: won't pass AMO review) to inject jquery into random pages, as this might interfere with the jquery version that might have been already loaded by a page (or whatever else the site assigned to $).

Instead it would be better if all your code would reside in your content script(s).

Upvotes: 3

willlma
willlma

Reputation: 7543

See the docs for loading content scripts. contentScriptFile accepts an array as an argument, so you can attach multiple scripts.

That said, page scripts (like your hello world) and content scripts cannot share variables for security reasons. It can be circumvented, but i can't imagine why there would be jQuery code on an HTML page that doesn't inject jQuery itself.

Upvotes: 1

Related Questions