Get cookies #99
Answered
by
wang0618
mawoka-myblock
asked this question in
Q&A
Get cookies
#99
-
Hello everyone, do you know a way to read a cookie or the localStorage for example and get this variable in the python thread, session? Thanks for your help! |
Beta Was this translation helpful? Give feedback.
Answered by
wang0618
May 16, 2021
Replies: 1 comment 18 replies
-
You can use This is an example to write and read the localStorage: key = 'name'
value = 'pywebio'
run_js("localStorage.setItem(key, value)", key=key, value=value)
val = eval_js("localStorage.getItem(key)", key=key) Since there is no direct functions to manipulate cookies in js, you need some helper functions: # https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript
run_js("""
window.setCookie = function(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
window.getCookie = function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
""")
run_js("setCookie(key, value)", key='name', value='pywebio')
val = eval_js("getCookie(key)", key='name')
run_js("setCookie(key, value)", key='hello', value='world')
val = eval_js("getCookie(key)", key='hello') |
Beta Was this translation helpful? Give feedback.
18 replies
Answer selected by
mawoka-myblock
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use
pywebio.session.run_js
andpywebio.session.eval_js
to deal with cookies or localStorage with js.This is an example to write and read the localStorage:
Since there is no direct functions to manipulate cookies in js, you need some helper functions: