最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to set cookie in new window? - Stack Overflow

programmeradmin1浏览0评论

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 .

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 .

Share Improve this question asked Aug 22, 2018 at 10:59 silvesterprabusilvesterprabu 1,45710 gold badges31 silver badges46 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

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.

发布评论

评论列表(0)

  1. 暂无评论