]> git.ardis.lu - ardislu.dev/commitdiff
Only show toast on the relevant page
authorArdis Lu <ardisglu@gmail.com>
Wed, 11 Jan 2023 03:19:46 +0000 (19:19 -0800)
committerArdis Lu <ardisglu@gmail.com>
Wed, 11 Jan 2023 03:19:46 +0000 (19:19 -0800)
Without this check, the toast is shown on all open tabs

script.js

index 8a32f2dabc560c2dd6132a3af55c0d7d768a698b..1f7479a0edfd9a8eb903901d8a22840761bc5b58 100644 (file)
--- a/script.js
+++ b/script.js
@@ -11,8 +11,14 @@ hljs.registerLanguage('solidity', solidity);
 navigator.serviceWorker?.register('/sw.js'); // serviceWorker is disabled on Firefox Private Browsing
 const cacheChannel = new BroadcastChannel('cache');
 cacheChannel.addEventListener('message', e => {
-  // Ignore static assets like logo.svg, style.css, script.js, etc. 
-  if (new URL(e.data.resource).pathname === '/api' && e.data.isUpdated) {
+  const resourceUrl = new URL(e.data.resource);
+  const isApiRequest = resourceUrl.pathname === '/api';
+  const isCurrentPage = resourceUrl.search.split('/').pop() === metadata.get(window.location.pathname).id;
+  // Only show toast if:
+  // - Non-static asset (static assets logo.svg, style.css, script.js, etc. are not managed by service worker)
+  // - The relevant page is open (if the user has multiple tabs open, do not show the toast on unrelated pages)
+  // - Data was changed
+  if (isApiRequest && isCurrentPage && e.data.isUpdated) {
     globalThis.components.get('toast').show();
   }
 });
This page took 0.05213 seconds and 4 git commands to generate.