我们可以从页面脚本中调用扩展功能吗?

时间:2019-03-02 03:08:23

标签: javascript google-chrome-extension

我的扩展程序中有一个功能:

function doStuff() {
  // Do stuff
}

我想从页面上的脚本中调用它:

<!doctype html>

<html>
  <head>
    <title>Extension Test</title>
    <script>doStuff();</script>
  </head>
  <body>
    <p>This is a test.</p>
  </body>
</html>

但是,控制台出现错误:

  

未捕获的ReferenceError:在(index):6处未定义doStuff

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

首先,您必须在manifest.json文件中添加以下代码:

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": [ "http://*/", "https://*/" ],
      "js": ["content.js"],
      "run_at": "document_start"
    }
  ],
  "permissions": [
    "http://*/",
    "https://*/"
  ]
  ...
}

现在您应该创建一个content.js文件,其内容为:

const injectedScript = document.createElement('script');
injectedScript.src = chrome.extension.getURL('injected.js');
(document.head || document.documentElement).appendChild(injectedScript);

然后创建一个injection.js文件,并在该文件中编写代码,例如:

function doStuff() {
  // Do stuff
}

我希望我明白你的意思。如果有问题,请告诉我。

相关问题