简体   繁体   中英

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=)

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).

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.

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