Electron cookie

纵然是瞬间 提交于 2019-12-20 03:17:39

问题


For electron cookie I used https://www.npmjs.com/package/electron-cookies

Then added this into my html

<script type="text/javascript">
require('electron-cookies')
function createCookie(name,value,days) {
    if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
                        document.cookie = name+"="+value+expires+"; path=/";
                    }

                    function getCookie12(name) {
                      var regexp = new RegExp("(?:^" + name + "|;\s*"+ name + ")=(.*?)(?:;|$)", "g");
                      var result = regexp.exec(document.cookie);
                      alert(document.cookie);
                      return (result === null) ? null : result[1];
                    }
    </script>

and called the methods :

<button onclick="createCookie('ppkcookie','testcookie',7)">Set Cookie</button>
<button onclick="getCookie12('ppkcookie')">Get Cookie</button>

but the alert(document.cookie) shows me only

ppkcookie not ppkcookie=testcookie

Any ideas why?

Many thanks


回答1:


This is how electron handles his own cookies.

var session = require('electron').remote.session;
var ses = session.fromPartition('persist:name');

This is how to set a cookie

     function setCookie(data, name) {
        var expiration = new Date();
        var hour = expiration.getHours();
        hour = hour + 6;
        expiration.setHours(hour);
        ses.cookies.set({
            url: BaseURL, //the url of the cookie.
            name: name, // a name to identify it.
            value: data, // the value that you want to save
            expirationDate: expiration.getTime()
        }, function(error) {
            /*console.log(error);*/
        });
    }

This is how to get the value of the cookie

    function getCookie(name) {
        var value = {
            name: name // the request must have this format to search the cookie.
        };
        ses.cookies.get(value, function(error, cookies) {
            console.console.log(cookies[0].value); // the value saved on the cookie
        });
    }

For more information about the cookies of electron you can read here



来源:https://stackoverflow.com/questions/39332058/electron-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!