Search code examples
javascriptgreasemonkeytampermonkey

Clear all cookies in a userscript?


How to clear all cookies or at least restart the browser in a tampermonkey/greasemonkey script?


Solution

  • To clear the cookies edit your Chrome shortcut (or write a shell script in Linux/MacOS) and add

     --remote-debugging-port=1234
    

    (or use a random port number that's not used by other processes) so you can send Network.clearBrowserCookies RDP command:

    // ==UserScript==
    // @name        Clear cookies
    // @match       https://www.example.org/*
    // @grant       GM_xmlhttpRequest
    // @connect     localhost
    // ==/UserScript==
    
    GM_xmlhttpRequest({
      url: 'http://localhost:1234/json',
      responseType: 'json',
      method: 'GET',
      onload(e) {
        const ws = new WebSocket(e.response[0].webSocketDebuggerUrl);
        ws.onopen = () => {
          ws.send(JSON.stringify({id: 1, method: 'Network.clearBrowserCookies'}));
        };
        ws.onerror = console.warn;
      },
    });