javascript - 从chrome扩展的background.js获取响应

标签 javascript jquery google-chrome google-chrome-extension

我想从后台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});
    });

                }
} 
 );

ma​​nifest.json 权限

"permissions": [
"tabs",
"storage",
"cookies",
"web_accessible_resources",
"<all_urls>"     
],

最佳答案

您可以使用message passing在扩展程序及其内容脚本之间建立通信。 。详细而言,由于内容脚本在网页而不是扩展程序的上下文中运行,因此它们通常需要某种方式与扩展程序的其余部分进行通信。

根据您的需要,从下面列出的不同类型的消息传递中进行选择:

  1. 简单的一次性请求

    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 or tabs.sendMessage.

  2. 长期连接

    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 or tabs.connect, respectively.

  3. 跨扩展程序消息传送

    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/

相关文章:

javascript - jquery 1.6.2 适用于 Android 2.1 模拟器但不适用于 Samsung Galaxy S

javascript - 如何显示从 javascript 变量到 div id 的 html 标签?

c# - Asp.Net 如何从 jQuery 检索 JSON

jquery - 如何创建一个 float 在右下角且响应迅速的聊天框?

javascript - getElementById 给出结果加上字符串

google-chrome - 混合内容错误与警告

javascript - 将单击 javascript 事件应用于 JSP 中的 header 而不是使用 <a> 标记

javascript - 将 javascript 移至单独的文件,ajax 调用出现错误

c# - 如何使用 Mono.Security 设置 X509 SubjectAltName (SAN)?

javascript - Contenteditable div 输入问题(keyCode 13)