首页 > 解决方案 > Chrome Extension - not sending cookies in the request

问题描述

I've read tons of questions on SO, tried multiple things but to no luck. My question would be similar, but I'm posting because I've tried everything but still not succeeded.

I want to check whether there's a user session maintained at my server. I've a webservice which returns a boolean value, based on the cookies received.

It's the responsibility of the browser to send cookies (if any) while requesting the server. So, when I request via the chrome-extension, theoretically the browser should send along the cookies too. However, it does not.

Here's my code:-

content.js

fetch('https://zoffers.in/apis/shops/get_aff_url/', {
    credentials: 'include',
    mode: 'cors',
    async: false,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name: 'Hubot',
        login: 'hubot',
    })
})
.then(function(data) {

})
.catch(function(error) {

})

Manifest.json

{
    "manifest_version": 2,
    "version": "0.1",
    "content_scripts": [{
        "matches": [
            "https://*/*/"
        ],
        "js": ["js/content.js"],
        "run_at": "document_start"
    }],
    "browser_action": {
        // "default_icon": "icon.png",
        "default_popup": "popup.html",
        "default_title": "Click here!"
    },
    "permissions": [
        "identity",
        "identity.email",
        "tabs",
        "notifications",
        "cookies",
        "https://zoffers.in/"
    ]
}

What wrong am I doing? Can anyone please help me through it.

UPDATED

content.js

message = {
    'event_type': 'Event1',
}
chrome.runtime.sendMessage(message);

background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse){
        if(request.event_type === 'Event1'){
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
                fetch('https://zoffers.in/apis/shops/get_aff_url/', {
                    credentials: 'include',
                    mode: 'cors',
                    async: false,
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: 'Hubot',
                        login: 'hubot',
                    })
                })
                .then(function(data) {

                })
                .catch(function(error) {

                })
            }
        }
    }
);

Have added background.js to manifest.json file. But still not working.

标签: google-chrome-extension

解决方案


您可以使用标准Cookies api并访问任何可用 URL 的 cookie。


推荐阅读