【问题标题】:Setting cookie with Chrome extension and Selenium Webdriver使用 Chrome 扩展和 Selenium Webdriver 设置 cookie
【发布时间】:2018-06-14 22:15:37
【问题描述】:

当我获得 Selenium Webdriver 实例来打开页面时,我正在尝试使用 Chrome 扩展程序来设置 cookie。我尝试按照不同 Stack Overflow 帖子中建议的各种方式进行操作,但是当我打开页面检查器时,它们都没有显示。

清单 - 我确保列出对任何 URL 的权限:

{
    "name": "Test",
    "description": "Test",
    "version": "2.0",
    "manifest_version": 2,
    "permissions": ["cookies", "<all_urls>", "background", "tabs", "webRequest", "webRequestBlocking", "http://*/*"],    
    "background": {
        "scripts": ["background.js"],
        "persistent": true
    } ,
    "content_scripts": [
      {
        "matches": ["*://*/*"],
        "js": ["script.js"]          
      }
    ] 
}

后台 JS - 我多次尝试创建 cookie,但在我检查网页或后台页面时均未显示:

chrome.cookies.set({ url: "https://google.com/", name: "CookieVar0", value: "123" });

chrome.webRequest.onBeforeRequest.addListener(
        function(details) {

        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          chrome.tabs.sendMessage(tabs[0].id, {test: testVar}, function(response) {
            console.log("Response connected");
            setCookie();
            chrome.cookies.set({ url: "http://example.google.com", name: "CookieVar1", value: "123" });
          });
        });

        }, 
        ...

function setCookie(){
    console.log("Set Cookie");

    chrome.cookies.set({"name":"Sample1","url":"http://developer.chrome.com/extensions/cookies.html","value":"Dummy Data"},function (cookie){
        console.log(JSON.stringify(cookie));
        console.log(chrome.extension.lastError);
        console.log(chrome.runtime.lastError);
    });

}

内容脚本 - 我读到您通常不应该尝试从内容脚本中设置 cookie,但有些帖子提到了它,所以我还是尝试了:

window.addEventListener('load', loadEvent => {
    console.log("Test 321");
    // window.customlog = "Updated window!!!";
    let window = loadEvent.currentTarget;
    window.document.title='You changed me!';
    chrome.cookies.set({ url: "http://example.google.com", name: "CookieVar3", value: "123" });
});

【问题讨论】:

    标签: javascript google-chrome selenium-webdriver google-chrome-extension


    【解决方案1】:

    所以这不是一个完整的答案,但我意识到,无论您在 cookie 中放置什么 URL,它都将被归档在您正在运行扩展程序的页面的 url 下。所以 chrome.cookies.set({ url: "https://google.com/", name: "CookieVar0", value: "123" });正在工作,但它不在“https://google.com/”下,而是在“当前页面网址”下。在我更改格式以匹配一个设置 CookieVar0 之前,一个设置“Sample1”不起作用,然后就可以了。

    所以我仍然无法让它在任何地方都按预期工作,但至少有一些进展。希望这对某人有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 2019-10-11
      • 2014-03-08
      • 2019-03-21
      • 1970-01-01
      相关资源
      最近更新 更多