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

时间:2016-03-22 12:09:32

标签: 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
  }

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

ReferenceError:未定义someFunctionFromMySuperScript

是否有办法在不修改 mySuperScript.js 的情况下调用此函数?

3 个答案:

答案 0 :(得分:2)

您的代码存在多个问题:

  1. 正如您所注意到的,注入脚本(mySuperScript.js)中的函数和变量对内容脚本(contentScript.js)不是直接可见的。这是因为这两个脚本在不同的execution environments
  2. 中运行
  3. 使用通过<script>属性引用的脚本插入src元素不会立即导致脚本执行。因此,即使脚本在同一环境中运行,您仍然无法访问它。
  4. 要解决此问题,请首先考虑是否确实需要在页面中运行mySuperScript.js。如果您不从页面本身访问任何JavaScript对象,则无需注入脚本。您应该尽量减少页面本身运行的代码量,以避免冲突。

    如果您不必在页面中运行代码,则在mySuperScript.js之前运行contentScript.js,然后立即可以使用任何函数和变量(通常,via the manifest或由programmatic injection)。 如果由于某种原因,脚本确实需要动态加载,那么您可以在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();
    });
    

    如果你真的必须从脚本调用页面中的一个函数(即mySuperScript.js必须绝对在页面的上下文中运行),那么你可以注入另一个脚本(通过{{的任何技术) 3}})然后将消息传递回内容脚本(例如Building a Chrome Extension - Inject code in a page using a Content script)。

    例如:

    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);
    

    (在上面的示例中,我使用的是using custom events,Chrome 41 +支持

答案 1 :(得分:1)

这不起作用,因为您的内容脚本和注入的脚本live in different contexts:您在页面中注入的内容是在页面上下文中。

  1. 如果您只是想将代码动态加载到内容脚本上下文中,则无法通过内容脚本执行此操作 - 您需要请求后台页面代表您执行executeScript。< / p>

    // Content script
    chrome.runtime.sendMessage({injectScript: "mySuperScript.js"}, function(response) {
      // You can use someFunctionFromMySuperScript here
    });
    
    // Background script
    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
      if (message.injectScript) {
        chrome.tabs.executeScript(
          sender.tab.id,
          {
            frameId: sender.frameId},
            file: message.injectScript
          },
          function() { sendResponse(true); }
        );
        return true; // Since sendResponse is called asynchronously
      }
    });
    
  2. 如果您需要在页面上下文中注入代码,那么您的方法是正确的,但您无法直接调用它。使用其他方法与其进行通信,例如custom DOM events

答案 2 :(得分:0)

只要someFunctionFromMySuperScript函数是全局函数,您就可以调用它,但是您需要等待实际加载的代码。

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');
      script.onload = function () {
          someFunctionFromMySuperScript(request.widgetFrame);         
      }
      head.appendChild(script);
  }

您也可以使用jQuery的getScript方法。

相关问题