是否可以创建一个Chrome扩展程序,可以执行属于正在浏览的页面的javascript函数?

时间:2012-11-05 19:53:37

标签: javascript google-chrome google-chrome-extension

  

可能重复:
  Building a Chrome Extension - Inject code in a page using a Content script

以下是我最初的尝试。首先,我创建了一个测试网页:

- test.html -

<HTML>
<SCRIPT src="script.js"></SCRIPT>
</HTML>

- script.js -

function testFunction() {
  console("function successfully run!");
}

然后我创建了一个非常简单的扩展,看看我是否可以从内容脚本运行testFunction():

- manifest.json -

{
  "name": "Function Test",
  "manifest_version": 2,
  "version": "1",
  "description": "An extension to experiment with running the javascript functions of the website being browsed.",
  "permissions": ["<all_urls>"],
  "content_scripts": [
    {
      "all_frames": true,
      "matches": ["<all_urls>"],
      "js": ["cs.js"],
      "run_at": "document_end"
    }
  ]
}

- cs.js -

scriptNodes = document.getElementsByTagName("script");
script = scriptNodes[0];
console.log(script.src);
script.testFunction();

这是控制台输出:

file:///C:/.../script.js
Uncaught TypeError: Object #<HTMLScriptElement> has no method 'testFunction'

那么,是否可以在使用Chrome扩展程序浏览的网站上运行某个功能?

1 个答案:

答案 0 :(得分:1)

似乎是不可能的。

请参阅#4658143http://code.google.com/chrome/extensions/content_scripts.html

  

但是,内容脚本有一些限制。他们不能:

     
      
  • 使用chrome。* API(chrome.extension的部分除外)
  •   
  • 使用其扩展程序页面定义的变量或函数
  •   
  • 使用由网页或其他内容脚本定义的变量或函数
  •