javascript - 将多个cookie值作为变量从background.js传递到contentscript.js

标签 javascript cookies google-chrome-extension

我正在尝试使用这个background.js获取cookie值

var myUrl = "https://cookiedomain.com/";

chrome.cookies.get({url: myUrl, name: 'email'}, function(cookie) {
     var email = cookie.value;
     chrome.runtime.sendMessage({ data: email });
});

chrome.cookies.get({url: myUrl, name: 'password'}, function(cookie) {
     var password = cookie.value;
     chrome.runtime.sendMessage({ data: password });
});

并获取电子邮件、密码作为 content.js 中的变量

 chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
      var email = request.email;
      var password = request.password;
    });

  ....

document.getElementById('id').value = email;

document.getElementById('id1').value = password ;

但似乎不起作用,有人可以帮我吗?

感谢大家。

最佳答案

您的代码中有几个问题:chrome.tabs.sendMessage 应该与选项卡 ID 一起使用,两行 document.getElementById 行应该位于 onMessage 回调内,您的后台脚本是发送一个带有 data 属性的对象,但内容脚本需要 emailpassword

有一个更简单的方法:反转流程并让内容脚本向后台脚本发出请求,后台脚本将获取两个 cookie 并在单个响应中将它们发回。

后台脚本:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.topic === 'getAuth') {
    chrome.cookies.get({url: msg.url, name: 'email'}, ({value: email}) => {
      chrome.cookies.get({url: msg.url, name: 'password'}, ({value: password}) => {
        sendResponse({email, password});
      });
    });
    // keep sendResponse channel open
    return true;
  }
});

内容脚本:

chrome.runtime.sendMessage({
  topic: 'getAuth',
  url: location.href,
}, ({email, password}) => {
  document.getElementById('id').value = email;
  document.getElementById('id1').value = password;
});

关于javascript - 将多个cookie值作为变量从background.js传递到contentscript.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55835202/

相关文章:

google-chrome-extension - Google Universal Analytics - 开发和调试工具

javascript - 停止页面加载并在内容脚本中重定向

javascript - PhantomJS 从 "json+ld"以外的 html 快照中删除脚本标签

authentication - 允许在网站上进行匿名/未经身份验证投票的编程策略

python - 将 cookie 添加到 cookiejar

c# - 在没有 asp 的情况下,在创建新 cookie 之前检查声明(电子邮件)。使用 asp net 核心社交登录的核心身份存储

javascript - 简单存储和本地存储有什么区别?

javascript - 如何使用 segment 属性根据图表 js 中的值对线条/边框颜色进行着色?

javascript - 路由: Visible parameter value on hovering over ui-sref disappears when clicked

javascript - 如何通过 jQuery 和自定义 url 参数使用 cookie