[英]Get Response From background.js of chrome extension
I want to get cookie value from background js.Even though I am able to get cookie value in background but bot able to get cookie value in front js. 我想从后台js获取cookie的值。即使我能够在后台获取cookie的值,但是机器人也能够在前台js中获取cookie的值。
I want to just return value from background js to front. 我只想从后台js返回值到前面。
front.js front.js
$(document).on("click", ".darkbtn", function (event) {
chrome.extension.sendRequest({ msg: "startFunc" },function(d){
console.log(d);
});
});
background.js background.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 manifest.json权限
"permissions": [
"tabs",
"storage",
"cookies",
"web_accessible_resources",
"<all_urls>"
],
You may establish communication between extensions and their content scripts by using message passing . 您可以使用消息传递在扩展程序及其内容脚本之间建立通信。 As detailed, since content scripts run in the context of a web page and not the extension, they often need some way of communicating with the rest of the extension.
详细地说,由于内容脚本是在网页而不是扩展程序的上下文中运行的,因此它们通常需要某种与扩展程序其余部分进行通信的方式。
Choose from different types of message passing as listed below depending on what you need: 根据需要,从以下列出的不同类型的消息传递中进行选择:
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
.如果只需要向扩展的另一部分发送一条消息(并有选择地返回响应),则应使用简化的
runtime.sendMessage
或tabs.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.在这种情况下,可以分别使用
runtime.connect
或tabs.connect
来打开从内容脚本到扩展页面的长寿命通道,反之亦然。
In addition to sending messages between different components in your extension, you can use the messaging API to communicate with other extensions.
除了在扩展中的不同组件之间发送消息之外,您还可以使用消息传递API与其他扩展进行通信。 This lets you expose a public API that other extensions can take advantage of.
这使您可以公开其他扩展可以利用的公共API。
Important information and examples on how to execute message passing are given in the documentation. 文档中提供了有关如何执行消息传递的重要信息和示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.