簡體   English   中英

如何從注入的腳本調用函數?

[英]How to call a function from injected script?

這是我的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的情況下調用此函數?

您的代碼存在多個問題:

  1. 正如您所注意到的,注入腳本(mySuperScript.js)中的函數和變量對內容腳本(contentScript.js)不是直接可見的。 這是因為這兩個腳本在不同的執行環境中運行。
  2. 使用通過src屬性引用的腳本插入<script>元素不會立即導致腳本執行。 因此,即使腳本在同一環境中運行,您仍然無法訪問它。

要解決此問題,首先要考慮是否確實需要在頁面中運行mySuperScript.js 如果您不從頁面本身訪問任何JavaScript對象,則無需注入腳本。 您應該嘗試最小化頁面本身中運行的代碼量以避免沖突。

如果您不必在頁面中運行代碼,則在contentScript.js之前運行mySuperScript.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();
});

如果你真的必須從腳本調用頁面中的函數(即mySuperScript.js必須絕對在頁面上下文中運行),那么你可以注入另一個腳本(通過構建Chrome擴展中的任何技術- 注入代碼在使用內容腳本的頁面中 ),然后將消息傳遞回內容腳本(例如, 使用自定義事件 )。

例如:

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

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

這不起作用,因為您的內容腳本和注入的腳本存在於不同的上下文中 :您注入頁面的內容是在頁面上下文中。

  1. 如果您只想動態地將代碼加載到內容腳本上下文中,則無法通過內容腳本執行此操作 - 您需要請求后台頁面代表您執行executeScript

     // 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. 如果您需要在頁面上下文中注入代碼,那么您的方法是正確的,但您無法直接調用它。 使用其他方法與其進行通信,例如自定義DOM事件

只要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方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM