简体   繁体   中英

how to set cookie in new window?

I want to open new window by using window.open and I want to set new cookie for that new window . I have tried to set cookie by using below code

        window.open("https://mysite.n")
        var expires = (function(days){
                    date = new Date();
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 
                   1000));
                 return date.toUTCString();
           })(5);
      document.cookie ="mytestcookie=testcookie; expires="+expires+"; path=/";

After this code execution . When I tried to get this cookie in new window I am getting undefined . Please help to set cookie in new window .

Thanks in Advance .

You need to set the cookie before you load the new page. Just reorder your code so window.open is last.

This assumes that new page is on the same origin as the current page. If it isn't, you can't set a cookie. It would be a major security problem if you could record data in a datastore belonging to someone else's website.

Quentin is absolutely right, but there is a way if you really have to achieve this just use a Headless Chromium with for example Puppeteer. You can go to the page and afterwords set the Cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM