简体   繁体   English

Firefox插件SDK注入了jquery

[英]Firefox addon SDK inject jquery

The script in $(document).ready(...) doesn't work, any ideas why ? $(document).ready(...)中的脚本不起作用,任何想法为什么? It seems the script I try to inject is loaded in the end. 看来我尝试注入的脚本最终被加载了。

Here my code: 这是我的代码:

main.js main.js

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

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 的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=) 谢谢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" ). 您可以使用您描述的技术注入jquery,但是取决于contentScriptWhen您在page-mod选项中设置时,您将看不到.ready()因为内容脚本仅在load后附加( contentScriptWhen="end" (默认))或DOMContentLoadedcontentScriptWhen="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. 您可以使用contentScriptWhen="start" ,但此时可能还没有可以将<script>标记附加到的节点。

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 $ ). 但是,我应该提一下,强烈建议不要将jquery注入随机页面,因为这可能会干扰页面可能已经加载的jquery版本(或其他任何网站)分配给$ )。

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. contentScriptFile接受一个数组作为参数,因此您可以附加多个脚本。

That said, page scripts (like your hello world) and content scripts cannot share variables for security reasons. 也就是说,页面脚本(如您的hello world)和内容脚本出于安全原因无法共享变量。 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. 它可以被规避,但我无法想象为什么在HTML页面上会有jQuery代码不会注入jQuery本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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