【问题标题】:Not working loaded jquery file in the content_script in chrome extension在 chrome 扩展的 content_script 中加载的 jquery 文件不起作用
【发布时间】:2011-01-11 13:31:31
【问题描述】:

我是这个 chrome 扩展插件开发的新手。我正在使用这个 chrome 扩展开发一个新的插件。

我的要求是在没有该 js 文件时将 jquery.js 文件加载到内容脚本中(例如:我正在检查 jquery.js 文件、fancybox.js 文件,如果不存在则加载这些文件。 )

当我在内容脚本中实现这个逻辑时,它正在加载 jquery.js 文件。之后它在内容脚本中不起作用。它显示 $(or) jQuery 未定义。每次加载,但不在内容脚本中执行。

这是我实现的代码。

document.getElementById('someid').onclick = loadJs();

function loadJS() {
if(tyof jQuery == undefined || tyof jQuery != 'function' )
  {
var jqscript = document.createElement('script');
jqscript.type = 'text/javascript';
jqscript.async = true;
// Src of the script
jqscript.src = "......url to jquery.js file..............";

// Check whether script is loaded or not
        jqscript.onload=function(){
            if ((!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
                    console.log("Script loaded - ");
                                   // It is showing error here
                                        alert(typeof jQuery);

            }
        };

// Get the document header
var head = document.getElementsByTagName('head')[0];
// Add script to header - otherwise IE complains
head.appendChild(jqscript);

}
}

请就此提出建议。

谢谢。

【问题讨论】:

  • 如果你想让人们回答你的问题,你应该努力正确地格式化你的问题和代码。
  • 你在那里称“内容脚本”有很多不同的东西。从您的代码看来,您正在尝试将 jquery 从内容脚本注入到父文档。如果您希望它在此之后也能在内容脚本中工作,那么它不会,因为内容脚本无权访问父文档变量。您能否重写您的问题并将内容脚本与父文档概念分开? (还有 0% 的比例是怎么回事?)

标签: jquery google-chrome-extension


【解决方案1】:

Chrome 扩展程序无法访问网页加载和使用的脚本。

Google 将这个孤立的世界称为:

http://code.google.com/chrome/extensions/content_scripts.html

你不能……

使用由其扩展页面定义的变量或函数

使用网页或其他内容脚本定义的变量或函数

所以,有什么脚本并不重要。重要的是在清单中包含所需的脚本:

"content_scripts": ['jquery.js', 'myScript.js', 'optionsScript.js'],

列表的顺序很重要,所以如果你的脚本使用 jquery,那么 jquery.js 应该在它之前。

【讨论】:

  • 谢谢你,哈利。你的编辑更清晰/更干净:)
猜你喜欢
  • 2012-09-19
  • 1970-01-01
  • 2023-03-11
  • 2016-07-22
  • 2017-03-12
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2013-12-28
相关资源
最近更新 更多