Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I also wanted to read a cookie (that had been set on the server) on the client. I worked around the issue by base64 encoding the JSON String, however there are a few small gotchas involved with this approach as well.</p> <p>1: Base64 strings end with 0-2 equal signs, and these were being converted into the string \075. My approach is to revert those characters into equal characters on the client.</p> <p>2: The base64 string is being enclosed in double quote characters in the cookie. I remove these on the client.</p> <p>Server:</p> <pre><code>nav_json = json.dumps(nav_data) nav_b64=base64.b64encode(nav_json) self.response.set_cookie('nav_data', nav_b64) </code></pre> <p>Client:</p> <pre><code>var user_data_base64= $.cookie('nav_data'); // remove quotes from around the string user_data_base64 = user_data_base64.replace(/"/g,""); // replace \075 with = user_data_base64 = user_data_base64.replace(/\\075/g,"="); var user_data_encoded=$.base64.decode( user_data_base64 ); var user_data = $.parseJSON(user_data_encoded); </code></pre> <p>I am using 2 jquery plugins here: <a href="https://github.com/carlo/jquery-base64" rel="nofollow">https://github.com/carlo/jquery-base64</a> and <a href="https://github.com/carhartl/jquery-cookie" rel="nofollow">https://github.com/carhartl/jquery-cookie</a></p> <p>Note: I consider this a hack: It would be better to re-implement the python code that encodes the cookie in javascript, however this also has the downside that you would need to notice and port and changes to that code.</p> <p>I have now moved to a solution where I use a small html file to set the cookie on the client side and then redirect to the actual page requested. Here is a snippet from the JINJA2 template that I am using:</p> <pre><code>&lt;script type="text/javascript"&gt; var nav_data='{% autoescape false %}{{nav_data}}{% endautoescape %}'; $.cookie('nav_data', nav_data, { path: '/' }); window.location.replace("{{next}}") &lt;/script&gt; </code></pre> <p>Note 2: Cookies are not ideal for my use case and I will probably move on to Session or Local Storage to reduce network overhead (although my nav_data is quite small - a dozen characters or so.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload