如何从注入的脚本调用函数?

ask*_*ona 5 javascript google-chrome google-chrome-extension

这是来自我的contentScript.js 的代码:

function loadScript(script_url)
  {
      var head= document.getElementsByTagName('head')[0];
      var script= document.createElement('script');
      script.type= 'text/javascript';
      script.src= chrome.extension.getURL('mySuperScript.js');
      head.appendChild(script);
      someFunctionFromMySuperScript(request.widgetFrame);// ReferenceError: someFunctionFromMySuperScript is not defined
  }
Run Code Online (Sandbox Code Playgroud)

但是从注入的脚本调用函数时出现错误:

ReferenceError: someFunctionFromMySuperScript 未定义

有没有办法在不修改mySuperScript.js 的情况下调用这个函数?

Rob*_*b W 2

您的代码存在多个问题:

  1. 正如您所注意到的,注入脚本 (mySuperScript.js) 中的函数和变量对于内容脚本 (contentScript.js) 并不直接可见。这是因为两个脚本运行在不同的执行环境中。
  2. 插入<script>带有通过src属性引用的脚本的元素不会立即导致脚本执行。因此,即使脚本在同一环境中运行,您仍然无法访问它。

mySuperScript.js要解决这个问题,首先要考虑是否真的有必要在页面中运行。如果您不从页面本身访问任何 JavaScript 对象,则无需注入脚本。您应该尽量减少页面本身运行的代码量以避免冲突。

如果您不必运行页面中的代码,则运行mySuperScript.jsbefore contentScript.js,然后任何函数和变量都立即可用(像往常一样,通过清单或通过编程注入)。如果由于某种原因脚本确实需要动态加载,那么您可以声明它web_accessible_resources并使用fetchXMLHttpRequest加载脚本,然后eval在内容脚本的上下文中运行它。

例如:

function loadScript(scriptUrl, callback) {
    var scriptUrl = chrome.runtime.getURL(scriptUrl);
    fetch(scriptUrl).then(function(response) {
        return response.text();
    }).then(function(responseText) {
        // Optional: Set sourceURL so that the debugger can correctly
        // map the source code back to the original script URL.
        responseText += '\n//# sourceURL=' + scriptUrl;
        // eval is normally frowned upon, but we are executing static
        // extension scripts, so that is safe.
        window.eval(responseText);
        callback();
    });
}

// Usage:
loadScript('mySuperScript.js', function() {
    someFunctionFromMySuperScript();
});
Run Code Online (Sandbox Code Playgroud)

如果您确实必须从脚本调用页面中的函数(即必须绝对在页面上下文中运行),那么您可以注入另一个脚本(通过构建 Chrome 扩展 - 在页面中注入代码中mySuperScript.js的任何技术)使用内容脚本),然后将消息传递回内容脚本(例如使用自定义事件)。

例如:

var script = document.createElement('script');
script.src = chrome.runtime.getURL('mySuperScript.js');
// We have to use .onload to wait until the script has loaded and executed.
script.onload = function() {
    this.remove(); // Clean-up previous script tag
    var s = document.createElement('script');
    s.addEventListener('my-event-todo-rename', function(e) {
        // TODO: Do something with e.detail
        // (= result of someFunctionFromMySuperScript() in page)
        console.log('Potentially untrusted result: ', e.detail);
        // ^ Untrusted because anything in the page can spoof the event.
    });
    s.textContent = `(function() {
        var currentScript = document.currentScript;
        var result = someFunctionFromMySuperScript();
        currentScript.dispatchEvent(new CustomEvent('my-event-todo-rename', {
            detail: result,
        }));
    })()`;

    // Inject to run above script in the page.
    (document.head || document.documentElement).appendChild(s);
    // Because we use .textContent, the script is synchronously executed.
    // So now we can safely remove the script (to clean up).
    s.remove();
};
(document.head || document.documentElement).appendChild(script);
Run Code Online (Sandbox Code Playgroud)

(在上面的示例中,我使用的是 Chrome 41+ 支持的模板文字)