在内容脚本和后台页面之间建立通信链接

use*_*400 0 javascript google-chrome background-process google-chrome-extension

使用javascript开发chrome扩展是我的大学项目之一.

我不知道如何使用消息传递在内容脚本和后台页面之间建立通信链接.我需要一些帮助来建立连接

background.html

chrome.tabs.getSelected(null, function(tab) { 
    chrome.tabs.sendRequest(tab.id, {method: "getHTML"}, function(response) { 
        console.log(response.data); 
    }); 
}); 
Run Code Online (Sandbox Code Playgroud)

content_script.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    if (request.method == "getHTML") 
        sendResponse({data: document.getElementById('header').innerHTML}); 
    else sendResponse({}); 
});
Run Code Online (Sandbox Code Playgroud)

bry*_*mck 6

一些主要问题:

  1. 您依赖于具有ID的页面上的某些元素header.这些ID由网站设计师自行决定,因此实际上很少有网页(包括Google).也许去寻找一些更普遍的东西,比如页面标题(document.title).
  2. "扩展按钮"是什么意思?如果它意味着浏览器操作,这是您的扩展的一部分,那么您想要从后台脚本发送内容是正确的.这也是一个更容易的情况,因为除了上面没有带有ID元素的Google页面的问题之外header,你可能只是没有捕获浏览器动作点击事件.但是,如果它是一些注入的按钮,那就是另一种方式.

你想要什么(浏览器动作版)

background.html(内联):

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, { method: "getHTML"}, function(response) {
      console.log(response.data);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

content_script.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.method === "getHTML") {
    sendResponse({data: document.title});
  } else {
    sendResponse({});
  }
});
Run Code Online (Sandbox Code Playgroud)

你可能想要什么(注入按钮点击版本)

background.html:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.method === "getHTML") {
    console.log(request.data);
  }
});
Run Code Online (Sandbox Code Playgroud)

content_script.js:

function buttonClick() {
  chrome.extension.sendRequest({method: "getHTML", data: document.title});
}
Run Code Online (Sandbox Code Playgroud)

以下评论回复代码

非常重要的建议:Chrome的开发人员参考可能是最友好的参考之一.如果您想知道chrome.*API的哪些部分可用,请从那里开始.

function getHtml(tabId) {
  chrome.tabs.sendRequest(tabId, { method: "getHTML"}, function(response) {
    console.log(response.data);
  });
}

// Note that this will only work once a tab has loaded
chrome.tabs.onSelectionChanged.addListener(function(tabId) {
  getHtml(tabId);
});

// This fires the first time a page is loaded
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
  if (changeInfo.status === "complete") {
    getHtml(tabId);
  }
});
Run Code Online (Sandbox Code Playgroud)

以下评论的第二回复代码

background.html

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.method === "getHTML") {
    console.log(request.data);
  }
});
Run Code Online (Sandbox Code Playgroud)

content_script.js

document.addEventListener("keypress", function(e) {
  chrome.extension.sendRequest({method: "getHTML", data: e.which});
});
Run Code Online (Sandbox Code Playgroud)