我想从后台js获取cookie值。即使我能够在后台获取cookie值,但机器人能够在前面js获取cookie值。
我只想将值从后台 js 返回到前台。
front.js
$(document).on("click", ".darkbtn", function (event) {
chrome.extension.sendRequest({ msg: "startFunc" },function(d){
console.log(d);
});
});
背景.js
function getCookies(domain, name, callback) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
if(callback) {
callback(cookie.value);
}
});
}
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse){
if(request.msg == "startFunc")
{
getCookies("http://localhost", "api_key", function(id) {
//getCookies("http://developer.chrome.com/extensions/cookies.html", "Sample1", function(id) {
sendResponse({data:id});
});
}
}
);
manifest.json 权限
"permissions": [
"tabs",
"storage",
"cookies",
"web_accessible_resources",
"<all_urls>"
],
最佳答案
您可以使用message passing在扩展程序及其内容脚本之间建立通信。 。详细而言,由于内容脚本在网页而不是扩展程序的上下文中运行,因此它们通常需要某种方式与扩展程序的其余部分进行通信。
根据您的需要,从下面列出的不同类型的消息传递中进行选择:
- 简单的一次性请求
If you only need to send a single message to another part of your extension (and optionally get a response back), you should use the simplified
runtime.sendMessage
ortabs.sendMessage
. - 长期连接
Sometimes it's useful to have a conversation that lasts longer than a single request and response. In this case, you can open a long-lived channel from your content script to an extension page, or vice versa, using
runtime.connect
ortabs.connect
, respectively. - 跨扩展程序消息传送
In addition to sending messages between different components in your extension, you can use the messaging API to communicate with other extensions. This lets you expose a public API that other extensions can take advantage of.
文档中给出了有关如何执行消息传递的重要信息和示例。
关于javascript - 从chrome扩展的background.js获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37669839/