簡體   English   中英

Chrome DevTools 和擴展中的內容腳本之間的通信

[英]Communicating between Chrome DevTools and content script in extension

(我已經閱讀了這個,但它沒有用,我做了很多搜索和實驗都無濟於事。)

我正在編寫一個 Chrome 擴展程序 ( BigConsole ),目的是為 Chrome 開發人員工具構建一個更好的控制台選項卡。 這意味着我想在頁面上下文中執行用戶輸入代碼,並可以訪問頁面上的 DOM 和其他變量。 為此,通信的結構如下:

  • devtools創建一個panel供用戶編寫代碼
  • 當用戶想要從panel執行代碼時, panel向帶有代碼的background腳本發送一條消息。
  • background腳本從panel接收消息/代碼並將其傳遞給注入頁面的content腳本
  • content腳本從background腳本接收消息/代碼,並將script元素注入頁面,然后運行代碼
  • 頁面上script的結果然后通過 window.postMessage 回發到content腳本
  • content腳本偵聽來自頁面的消息/結果並將其傳遞給background腳本
  • background腳本從content腳本接收消息/結果並將其傳遞給panel
  • panelbackground腳本接收消息/結果並將其插入到結果日志中

哇。

現在,當用戶嘗試運行代碼時,什么也沒有發生。 我將一堆console.log()放入代碼中,但控制台中什么也沒出現。 我的主要問題是,我在傳遞消息時做錯了什么,導致什么也沒有發生? 或者,我很想被告知我讓這種方式太復雜了,並且有更好的做事方式。 下面的簡化代碼...

面板.js:

    window.onload = function() {
      var port = chrome.runtime.connect({name: "Eval in context"});
      // Add the eval'd response to the console when the background page sends it back
      port.onMessage.addListener(function (msg) {
        addToConsole(msg, false);
      });
      document.getElementById('run').addEventListener('click', function() {
        var s = document.getElementById('console').value;
        try {
          // Ask the background page to ask the content script to inject a script
          // into the DOM that can finally eval `s` in the right context.
          port.postMessage(s);
          // Outputting `s` to the log in the panel works here,
          // but console.log() does nothing, and I can't observe any
          // results of port.postMessage
        }
        catch(e) {}
      });
    };

背景.js:

    chrome.runtime.onConnect.addListener(function (port) {
      // Listen for message from the panel and pass it on to the content
      port.onMessage.addListener(function (message) {
        // Request a tab for sending needed information
        chrome.tabs.query({'active': true,'currentWindow': true}, function (tabs) {
          // Send message to content script
          if (tab) {
            chrome.tabs.sendMessage(tabs[0].id, message);
          }
        });
      });
      // Post back to Devtools from content
      chrome.runtime.onMessage.addListener(function (message, sender) {
        port.postMessage(message);
      });
    });

內容.js:

    // Listen for the content to eval from the panel via the background page
    chrome.runtime.onMessage.addListener(function (message, sender) {
      executeScriptInPageContext(message);
    });
    function executeScriptInPageContext(m) { alert(m); }

正如亞歷克斯所指出的,這是您的代碼中的一個錯字,它阻止了它的工作。

刪除當前代碼並使用chrome.devtools.inspectedWindow.eval直接運行代碼並解析結果。 這將您復雜的邏輯簡化為:

  • devtools 創建一個面板供用戶編寫代碼
  • devtools 運行代碼
  • devtools 處理結果

附注。 一種方法來處理現有的控制台,但我建議不要使用它,除非是供個人使用。 這個答案顯示了兩種不同的方法來做到這一點

暫無
暫無

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

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