javascript - Google Chrome Extension - content_scripts 与 background_page js 文件通信

标签 javascript google-chrome google-chrome-extension

在我的 Google Chrome 扩展程序中,我有一个 content_script 想要与我的 background_page 进行通信。有谁知道如何做到这一点?

我找到了一些教程,介绍了背景页面如何与 content_script 通信,但正如我所说,我需要相反的情况发生。

我想运行一个自动脚本来每 24 小时清除一次缓存。我不能从 content_script 执行此操作,我必须从后台页面执行此操作。我现在可以让它工作的唯一方法是绑定(bind)一个“按钮”,但正如我之前所说,我希望它每 24 小时自动运行一次。

顺便说一句,我已经知道内容脚本不能: 使用 chrome.* API(chrome.extension 部分除外) 使用由其扩展页面定义的变量或函数 使用网页或其他内容脚本定义的变量或函数

如您所见,列出的第一项是:chrome API,但我需要在我的 content_script 中使用 chrome API,所以希望有人可以解决。请告诉我。

最佳答案

Message Passing Doc from Google

内容脚本:

chrome.extension.sendRequest({greeting: "hello"}, function(response) { //request
  console.log(response.farewell);           //receive response
});

背景页面:

chrome.extension.onRequest.addListener(     //listen to requests
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});  //send response
  });

您还可以在内容脚本和后台页面之间建立长期连接:
http://code.google.com/chrome/extensions/messaging.html#connect

contentscript.js
================
var port = chrome.extension.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
      if (msg.question == "Who's there?")
    port.postMessage({answer: "Madame"});
  else if (msg.question == "Madame who?")
    port.postMessage({answer: "Madame... Bovary"});
});


background.html
===============
chrome.extension.onConnect.addListener(function(port) {
  console.assert(port.name == "knockknock");
  port.onMessage.addListener(function(msg) {
    if (msg.joke == "Knock knock")
      port.postMessage({question: "Who's there?"});
    else if (msg.answer == "Madame")
      port.postMessage({question: "Madame who?"});
    else if (msg.answer == "Madame... Bovary")
      port.postMessage({question: "I don't get it."});
  });
});

关于javascript - Google Chrome Extension - content_scripts 与 background_page js 文件通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972399/

相关文章:

javascript - 无法让 console.log() 在 popup.js 中工作

javascript - Angular 指令模板抛出错误

javascript - C++11 标准引用 ECMAScript (Javascript) 规范?

javascript - indexeddb:如何获取请求结果和游标值

google-chrome - Chrome中的重复标签复制sessionStorage

google-chrome - listbox.js 或 pickers.js 未从 sv-se 加载,错误 404

javascript - 使用 jquery 悬停时显示文本

node.js - Chrome 扩展程序中的 Origin header

javascript - 除了浏览器设置之外,还可以从弹出菜单更改 Chrome 扩展语言

google-chrome - 是否可以在 Chrome Web 检查器网络选项卡中隐藏扩展程序资源?