Browse Source

fix: disabling cookies doesn't crash script anymore

Sv443 1 year ago
parent
commit
b95ac86a30
2 changed files with 14 additions and 6 deletions
  1. 2 0
      contributing.md
  2. 12 6
      src/utils/misc.ts

+ 2 - 0
contributing.md

@@ -305,6 +305,8 @@ The usage and example blocks on each are written in TypeScript but can be used i
 > Description:  
 > Returns the unique session ID that is generated on every page load.  
 > It should persist between history navigations, but not between page reloads.  
+>  
+> ⚠️ On privacy-focused browsers or if cookies are disabled, this function will return null since sessionStorage is not available.
 >   
 > <details><summary><b>Example <i>(click to expand)</i></b></summary>
 > 

+ 12 - 6
src/utils/misc.ts

@@ -20,14 +20,20 @@ export function getDomain(): Domain {
     throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
 }
 
-/** Returns a pseudo-random ID unique to each session */
-export function getSessionId(): string {
-  let sesId = window.sessionStorage.getItem("_bytm-session-id");
+/** Returns a pseudo-random ID unique to each session - returns null if sessionStorage is unavailable */
+export function getSessionId(): string | null {
+  try {
+    let sesId = window.sessionStorage.getItem("_bytm-session-id");
 
-  if(!sesId)
-    window.sessionStorage.setItem("_bytm-session-id", sesId = randomId(8, 36));
+    if(!sesId)
+      window.sessionStorage.setItem("_bytm-session-id", sesId = randomId(8, 36));
 
-  return sesId;
+    return sesId;
+  }
+  catch(err) {
+    warn("Couldn't get session ID, sessionStorage / cookies might be disabled:", err);
+    return null;
+  }
 }
 
 //#SECTION resources