4

可能重复:
构建 Chrome 扩展 - 使用内容脚本在页面中注入代码

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

- test.html -

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

- 脚本.js -

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

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

- 清单.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 扩展程序在您正在浏览的网站上运行功能?

4

1 回答 1

1

似乎是不可能的。

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

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

  • 使用 chrome.* API(chrome.extension 的部分除外)
  • 使用由其扩展页面定义的变量或函数
  • 使用由网页或其他内容脚本定义的变量或函数
于 2012-11-05T20:40:00.253 回答