user11127627
user11127627

Reputation:

Is there a way to ask if part of a domain is included in document.referrer?

I'm setting up a modal for our website, and we want it to only appear if a user is coming into any of our pages from an external page (i.e. from google to our page). The modal should show up on all pages, so I have it set up in our header since that's one of two sections that is constant throughout our site (the other being the footer). I have a modal coming in for certain pages using a document.referrer conditional, but the code is set up that I would have to literally type out every single other url in our website (over 500 pages) in order for that to work.

So the question is, is there a way I can target the domain URL in a conditional, where if the domain is included in the previous page (referrer) url, then don't show the modal?

Here is the example of the modal I have now:

const domains = ["http://website.com/*"];

            if (domains.includes(document.referrer)) {
              console.log("Don't Show Modal - from any park page", document.referrer);
            } else {
              console.log("Show Modal - From other Page", document.referrer);

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

            }

#closureModal is connected to the modal HTML code.

Upvotes: 1

Views: 135

Answers (1)

esqew
esqew

Reputation: 44701

You could leverage the URL interface to perform this comparison. You'll have to use hostnames in your domains array (i.e., no protocol or path) or process the entries in domains through URL as well, but either way it should be pretty robust for what you need it to do.

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

if (domains.includes(referrer_hostname)) {
  console.log("Don't Show Modal - from any park page", document.referrer);
} else {
  console.log("Show Modal - From other Page", document.referrer);
  /* modal manipulation */
}

Upvotes: 0

Related Questions