1

I'm writing a chrome extension where I simply want to be able to add and remove a specifc cookie in the same way document.cookie='name=val' does.

However the cookie does not seem to write from my popup.js file. Is this possible?

So far this is my extension:

Manifest.json

{
    "manifest_version": 2,
    "name": "Cookie Extension",
    "version": "0.1",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "permissions": [
        "cookies",
        "<all_urls>"
    ]
}

popup.html

<!doctype html>
<html>
    <head>
        <title>Cookie Extension</title>
        <script src="popup.js"></script>
    </head>
    <body>
        <h1>Test</h1>
        <div class="wrapper">
    `   <label class="switch">
            <input id="toggle" type="checkbox">
            <span class="slider"></span>
        </label>
    </body>
</html>

popup.js

window.onload = function(){
    const wrapper = document.querySelector('.wrapper');

    wrapper.addEventListener('change', function(e) {
        if (e.target.checked) {
            document.cookie='testCookie=true';
        } else {
            document.cookie = "testCookie=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        }
    });
};
Community
  • 1
  • 1
samgbelton
  • 89
  • 1
  • 10
  • 1
    The popup is a separate page with chrome-extension:// protocol so it is not a part of the web page in the tab. See [How to access the webpage DOM rather than the extension page DOM?](https://stackoverflow.com/a/4532567), you can also use `chrome.cookies` API, see the documentation. – wOxxOm May 14 '20 at 18:05
  • Thank you @wOxxOm Moving the `document.cookie` to a content script works. – samgbelton May 14 '20 at 19:00

0 Answers0