Is there a way to set a cookie using JS and force a dynamic element reliant on the cookie to update without reloading the page?

36 views Asked by At

apologies if the title question is confusing, but I'm not entirely sure how to ask or phrase this. Basically, I want a button to trigger (it opens a popup) on page load—easy enough.

However, the button is a "Find a Location" thing, so upon a user's first-time (or cookie-less) visit, they see that button. If the user clicks it and inputs their location info, they get redirected to a page, and the button changes to one displaying their location, and the popup content also changes; the button gets fed a stored cookie with the location info, which is how the content updates.

I need to figure out a way to get this location info, via this cookie, injected on page load without the user having to enter their information at all, OR refreshing/navigating away from the page.

Right now, I have a function written to set the cookie upon load, and then automatically trigger the popup, but the button does not automatically update via the manual cookie setting unless the user reloads the page. I need everything to happen in one seamless motion. Is this feasible, or no?

I need to do this via Javascript, if it is even possible—no other methods, please. Also, this is not something I can do via the site's back end or some CMS either.

Thanks.

1

There are 1 answers

6
guest271314 On

I wouldn't try to use cookies.

You can use localStorage or navigator.storage.getDirectory() to achieve the requirement. On document load if the string or directory exists, get the data, else create the string or directory and files and write the data.

For example, here's how I fetch a an external library once, if the file is not set in navigator.storage, else I load an Ecmascript Module from the file stored in navigator.storage:

const dir = await navigator.storage.getDirectory();
const entries = await Array.fromAsync(dir.keys());
let handle;
if (!entries.includes("lames.js")) {
  handle = await dir.getFileHandle("lame.js", {
    create: true,
  });
  await new Blob([await (await fetch("https://raw.githubusercontent.com/guest271314/captureSystemAudio/master/native_messaging/capture_system_audio/lame.min.js", )).arrayBuffer(), ], {
    type: "text/javascript",
  }).stream().pipeTo(await handle.createWritable());
} else {
  handle = await dir.getFileHandle("lame.js", {
    create: false,
  });
}
const file = await handle.getFile();
const url = URL.createObjectURL(file);
const {
  lamejs
} = await import(url);
this.mp3encoder = new lamejs.Mp3Encoder(2, 44100, 192);
 

Note, technically it is possible to read localStorage and the data stored in navigator.storage, and when webkitRequestFileSystem is used from the browser configuration file, see How to write into a file (in user directory) using JavaScript?.