| // Cookieless session: a stable localStorage token sent as a header on every | |
| // /api fetch, and appended as ?sid= on <img> sprite URLs. Works inside HF | |
| // Spaces' cross-site iframe regardless of third-party-cookie policy. | |
| (function () { | |
| let sid = localStorage.getItem('weedsim_sid'); | |
| if (!sid) { | |
| sid = (window.crypto && crypto.randomUUID) | |
| ? crypto.randomUUID() | |
| : 'sid-' + Date.now() + '-' + Math.random().toString(36).slice(2); | |
| localStorage.setItem('weedsim_sid', sid); | |
| } | |
| window.WEEDSIM_SID = sid; | |
| // Append the session id to a sprite URL (for <img src>, which can't send headers). | |
| window.withSid = function (url) { | |
| return url + (url.indexOf('?') >= 0 ? '&' : '?') + 'sid=' + encodeURIComponent(sid); | |
| }; | |
| // Inject the header on all same-origin /api requests. | |
| const _fetch = window.fetch.bind(window); | |
| window.fetch = function (url, opts) { | |
| opts = opts || {}; | |
| try { | |
| if (typeof url === 'string' && url.indexOf('/api') === 0) { | |
| const h = new Headers(opts.headers || {}); | |
| h.set('X-WeedSim-Session', sid); | |
| opts.headers = h; | |
| } | |
| } catch (e) { /* never block a request over session wiring */ } | |
| return _fetch(url, opts); | |
| }; | |
| })(); | |