How to link to javascript file inside an express route











up vote
0
down vote

favorite












I am trying to configure push notifications on a NodeJS application that is modular. I have generated my VAPID keys already as well. I have a file, client.js, which registers my service worker (which sits in a separate file), registers my push and then sends it. It converts the public key to a Uint8 array format as well.



Now, in most use cases I have seen, the main HTML document links to this javascript file in the header inside the <script> tag. However, my header, footer and body are split up into separate EJS templates. If I link to this file in the header, it will trigger a push notification for every page in my application, since the header template is part of them all.



Therefore, I was wondering if there was a way to import this file into only the page which is mapped to a specific route path by passing it into the corresponding app.get() method?



I considered exporting the client.js file and passing it into the route definition as middleware, but I am not sure how to do this or if it is the right way to do it.



Here is client.js:



const publicVapidKey =
"********";

// Check for service worker
if ("serviceWorker" in navigator) {
send().catch(err => console.error(err));
}

// Register SW, Register Push, Send Push
async function send() {
// Register Service Worker
console.log("Registering service worker...");
const register = await navigator.serviceWorker.register("/worker.js", {
scope: "/"
});
console.log("Service Worker Registered...");

// Register Push
console.log("Registering Push...");
const subscription = await register.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
});
console.log("Push Registered...");

// Send Push Notification
console.log("Sending Push...");
await fetch("/subscribe", {
method: "POST",
body: JSON.stringify(subscription),
headers: {
"content-type": "application/json"
}
});
console.log("Push Sent...");
}

function urlBase64ToUint8Array(base64String) {
const padding = "=".repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/-/g, "+")
.replace(/_/g, "/");

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}


Could I export this as middleware to be called when the route is triggered? Also, exactly how would I do this? I am not sure this is the same thing as loading a .js file into the browser as is done using the script tag. Is there a better way to do that inside my route?



Thanks for your help in advance.










share|improve this question




























    up vote
    0
    down vote

    favorite












    I am trying to configure push notifications on a NodeJS application that is modular. I have generated my VAPID keys already as well. I have a file, client.js, which registers my service worker (which sits in a separate file), registers my push and then sends it. It converts the public key to a Uint8 array format as well.



    Now, in most use cases I have seen, the main HTML document links to this javascript file in the header inside the <script> tag. However, my header, footer and body are split up into separate EJS templates. If I link to this file in the header, it will trigger a push notification for every page in my application, since the header template is part of them all.



    Therefore, I was wondering if there was a way to import this file into only the page which is mapped to a specific route path by passing it into the corresponding app.get() method?



    I considered exporting the client.js file and passing it into the route definition as middleware, but I am not sure how to do this or if it is the right way to do it.



    Here is client.js:



    const publicVapidKey =
    "********";

    // Check for service worker
    if ("serviceWorker" in navigator) {
    send().catch(err => console.error(err));
    }

    // Register SW, Register Push, Send Push
    async function send() {
    // Register Service Worker
    console.log("Registering service worker...");
    const register = await navigator.serviceWorker.register("/worker.js", {
    scope: "/"
    });
    console.log("Service Worker Registered...");

    // Register Push
    console.log("Registering Push...");
    const subscription = await register.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
    console.log("Push Registered...");

    // Send Push Notification
    console.log("Sending Push...");
    await fetch("/subscribe", {
    method: "POST",
    body: JSON.stringify(subscription),
    headers: {
    "content-type": "application/json"
    }
    });
    console.log("Push Sent...");
    }

    function urlBase64ToUint8Array(base64String) {
    const padding = "=".repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
    .replace(/-/g, "+")
    .replace(/_/g, "/");

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
    }


    Could I export this as middleware to be called when the route is triggered? Also, exactly how would I do this? I am not sure this is the same thing as loading a .js file into the browser as is done using the script tag. Is there a better way to do that inside my route?



    Thanks for your help in advance.










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am trying to configure push notifications on a NodeJS application that is modular. I have generated my VAPID keys already as well. I have a file, client.js, which registers my service worker (which sits in a separate file), registers my push and then sends it. It converts the public key to a Uint8 array format as well.



      Now, in most use cases I have seen, the main HTML document links to this javascript file in the header inside the <script> tag. However, my header, footer and body are split up into separate EJS templates. If I link to this file in the header, it will trigger a push notification for every page in my application, since the header template is part of them all.



      Therefore, I was wondering if there was a way to import this file into only the page which is mapped to a specific route path by passing it into the corresponding app.get() method?



      I considered exporting the client.js file and passing it into the route definition as middleware, but I am not sure how to do this or if it is the right way to do it.



      Here is client.js:



      const publicVapidKey =
      "********";

      // Check for service worker
      if ("serviceWorker" in navigator) {
      send().catch(err => console.error(err));
      }

      // Register SW, Register Push, Send Push
      async function send() {
      // Register Service Worker
      console.log("Registering service worker...");
      const register = await navigator.serviceWorker.register("/worker.js", {
      scope: "/"
      });
      console.log("Service Worker Registered...");

      // Register Push
      console.log("Registering Push...");
      const subscription = await register.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
      });
      console.log("Push Registered...");

      // Send Push Notification
      console.log("Sending Push...");
      await fetch("/subscribe", {
      method: "POST",
      body: JSON.stringify(subscription),
      headers: {
      "content-type": "application/json"
      }
      });
      console.log("Push Sent...");
      }

      function urlBase64ToUint8Array(base64String) {
      const padding = "=".repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding)
      .replace(/-/g, "+")
      .replace(/_/g, "/");

      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);

      for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
      }
      return outputArray;
      }


      Could I export this as middleware to be called when the route is triggered? Also, exactly how would I do this? I am not sure this is the same thing as loading a .js file into the browser as is done using the script tag. Is there a better way to do that inside my route?



      Thanks for your help in advance.










      share|improve this question















      I am trying to configure push notifications on a NodeJS application that is modular. I have generated my VAPID keys already as well. I have a file, client.js, which registers my service worker (which sits in a separate file), registers my push and then sends it. It converts the public key to a Uint8 array format as well.



      Now, in most use cases I have seen, the main HTML document links to this javascript file in the header inside the <script> tag. However, my header, footer and body are split up into separate EJS templates. If I link to this file in the header, it will trigger a push notification for every page in my application, since the header template is part of them all.



      Therefore, I was wondering if there was a way to import this file into only the page which is mapped to a specific route path by passing it into the corresponding app.get() method?



      I considered exporting the client.js file and passing it into the route definition as middleware, but I am not sure how to do this or if it is the right way to do it.



      Here is client.js:



      const publicVapidKey =
      "********";

      // Check for service worker
      if ("serviceWorker" in navigator) {
      send().catch(err => console.error(err));
      }

      // Register SW, Register Push, Send Push
      async function send() {
      // Register Service Worker
      console.log("Registering service worker...");
      const register = await navigator.serviceWorker.register("/worker.js", {
      scope: "/"
      });
      console.log("Service Worker Registered...");

      // Register Push
      console.log("Registering Push...");
      const subscription = await register.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
      });
      console.log("Push Registered...");

      // Send Push Notification
      console.log("Sending Push...");
      await fetch("/subscribe", {
      method: "POST",
      body: JSON.stringify(subscription),
      headers: {
      "content-type": "application/json"
      }
      });
      console.log("Push Sent...");
      }

      function urlBase64ToUint8Array(base64String) {
      const padding = "=".repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding)
      .replace(/-/g, "+")
      .replace(/_/g, "/");

      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);

      for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
      }
      return outputArray;
      }


      Could I export this as middleware to be called when the route is triggered? Also, exactly how would I do this? I am not sure this is the same thing as loading a .js file into the browser as is done using the script tag. Is there a better way to do that inside my route?



      Thanks for your help in advance.







      javascript express push-notification web-push asynccallback






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 at 11:50

























      asked Nov 12 at 20:33









      Eric R.

      437




      437





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269684%2fhow-to-link-to-javascript-file-inside-an-express-route%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269684%2fhow-to-link-to-javascript-file-inside-an-express-route%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)