【问题标题】:Pass multiple cookies value as variables from background.js to contentscript.js将多个 cookie 值作为变量从 background.js 传递到 contentscript.js
【发布时间】:2019-04-25 12:07:55
【问题描述】:

我正在尝试使用这个 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.cookies.getAll() 的结果是什么?

标签: javascript cookies google-chrome-extension


【解决方案1】:

您的代码中有几个问题: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;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2019-06-10
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多