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

Javascript 将多个cookie值作为变量从background.js传递到contentscript.js,javascript,cookies,google-chrome-extension,Javascript,Cookies,Google Chrome Extension,我正在尝试使用background.js获取cookies值 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:

我正在尝试使用background.js获取cookies值

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回调中,您的后台脚本正在发送一个包含数据属性的对象,但内容脚本需要电子邮件和密码

有一种更简单的方法:颠倒流程,让内容脚本向后台脚本发出请求,后台脚本将获取两个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;
});
chrome.cookies.getAll的结果是什么?