javascript Chrome 扩展 - onRequest/sendRequest 与 onMessage/sendMessage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11335815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:49:37  来源:igfitidea点击:

Chrome Extensions - onRequest/sendRequest vs onMessage/sendMessage

javascriptgoogle-chromegoogle-chrome-extension

提问by FRD

Checking out this sample extensionlinked by a page in the Chrome Extension center, I see they used

查看Chrome 扩展中心页面链接的这个示例扩展,我看到他们使用了

chrome.extension.onRequest.addListener(onRequest);

in the background.js page in order to listen to the contentscript.js and

在 background.js 页面中以收听 contentscript.js 和

  chrome.extension.sendRequest({}, function(response) {});

in the contentscript.js in order to talk to the background.js page.

在 contentscript.js 中,以便与 background.js 页面对话。

But I can't find the documentation for these functions anywhere in the web and Google's Message Passing guideonly mentions

但是我在网络上的任何地方都找不到这些功能的文档,而且谷歌的消息传递指南只提到了

chrome.extension.sendMessage(...)

to send, and

发送,和

chrome.extension.onMessage.addListener(...)

to listen.

听。

Which functions should I use? Is sendRequest/onRequest obsolete? Is the Google's dev guide still up-to-date?

我应该使用哪些功能?sendRequest/onRequest 过时了吗?Google 的开发指南是否仍然是最新的?

采纳答案by Achal Dave

It seems sendMessageis favored over sendRequest, which is to be deprecated: http://codereview.chromium.org/9965005/

它似乎sendMessage受到青睐sendRequest,但将被弃用:http: //codereview.chromium.org/9965005/

回答by peterthinking

Also note the change in API path from

还要注意 API 路径的变化

  • chrome.extension.onRequest
  • chrome.extension.sendRequest
  • chrome.extension.onRequest
  • chrome.extension.sendRequest

to

  • chrome.runtime.onMessage
  • chrome.runtime.sendMessage
  • chrome.runtime.onMessage
  • chrome.runtime.sendMessage

will save you getting frustrated over why e.g. chrome.extension.onMessage is not working!

将避免您对为什么例如 chrome.extension.onMessage 不起作用而感到沮丧!