Search code examples
javascriptconditional-statementsreferrerallow-modals

Modal doesn't show if user manually types in our url in address bar


The modal I've created displays when a user accesses our page from an external link (i.e. Google search result), but if a user enters our site by manually entering our URL into the address bar, an error occurs and the modal doesn't appear.

Here is my code:

  const siteUrl = ["website.com"];
  const referrer_hostname = new URL(document.referrer).hostname;

  if (siteUrl.includes(referrer_hostname)) {
    console.log("Don't Show Modal", document.referrer);
  } else {
    console.log("Show Modal", document.referrer);

    $( window ).on('load', function() {
      console.log("closure modal firing");
      $('#closureModal').modal({
        backdrop: 'static',
        keyboard: false,
        show: true
      });
    });

the #closureModal is connected to the HTML of the modal.

Error: (index):123 Uncaught TypeError: Failed to construct 'URL': Invalid URL


Solution

  • document.referrer is an empty string "" when you enter the URL into the address bar. Try addign a validation:

    const referrer_hostname = document.referrer !== "" ? new URL(document.referrer).hostname : "";
    

    this allows you to avoid the TypeError