使 Chrome 扩展 javascript 文档适用于打开网页,而不是弹出窗口

Make Chrome extension javascript document apply to open webpage, not popup

我正在编写 chrome 扩展程序,我需要在其中单击网页上的项目。可以使用 document.getElementsByClassName("className")[0].click() 找到该项目,但如果我在弹出窗口中使用 运行 ,它会在弹出菜单中搜索该项目。我怎样才能做到return并点击网页中的项目?

您应该制作一个 content script 并使用它来执行点击。内容脚本在 HTML 页面的上下文中加载,而不是扩展弹出窗口。

您可以使用 messaging API.

在内容脚本和主扩展代码之间发送消息

您的扩展代码可以像这样向内容脚本发送消息:


// Query the active tab in the current window (there will only be one)
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

  // Send a message to that tab (found as tabs[0]), 
  chrome.tabs.sendMessage(tabs[0].id, {message: "perform_click"}, function(response) {
    console.log("Click performed.");
  });
});

您的内容脚本可以像这样处理请求:


// Listen for events from the background script (main part of the extension)
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  // This function will be called in the content script to handle messages received from the main extension code.

  // If the extension is requesting a click, we do that here
  if (request.message == "perform_click") {
    document.getElementsByClassName("className")[0].click()
  }
});