The modal will not display if the user enters our URL manually in the address bar

The modal I've developed appears when a visitor lands on our website through an external link (such as from a Google search result). However, an error occurs and the modal fails to show up if the user manually types our URL into the address bar.

Below is the code snippet:

  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 element is linked to the HTML structure of the modal.

Error:

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

Answer №1

When typing a URL into the address bar, document.referrer becomes an empty string "" . To prevent any TypeError, consider implementing this validation:

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

By using this approach, you can handle potential errors effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``Can the content visible to an iframe be controlled by manipulating window.top?

There's a unique web application that functions by loading various iframes into itself. It offers some code that the child iframes can connect with. The child iframes use window.top, which is beyond my control but everything runs smoothly. Now, I ai ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

PHP application with seamless integration of barcode scanning technology

It's common knowledge that a barcode scanner functions as a keyboard, entering text into our forms when scanning a code. However, for this to work effectively, the cursor must be in the form field. In situations where input data is needed without rel ...

Placing content retrieved from a MySQL database within a form displayed in a ColorBox

Having difficulty inserting text from a MySQL database into a form (textfield) inside a ColorBox. The current script is as follows: <a href="#" class="bttn sgreen quote1">Quote</a> var postQuote[<?php echo 4id; ?>]=<?php echo $f ...

Invoking a function within a for loop in JavaScript

Here is the loop I am currently using: if (list.length) { for (let i = 0; i < list.length; i++) { let fruit = list[i].attributes; if (fruit.color === 'red') { id = fruit.id; frui ...

Having trouble retrieving data passed between functions

One of my Vue components looks like this: import '../forms/form.js' import '../forms/errors.js' export default{ data(){ return{ form: new NewForm({ email: '&apos ...

Function executed prior to populating $scope array

I encountered an issue with AngularJS involving a function that is called before the data array is filled. When the function is invoked in ng-init, the $scope.bookings array is not yet populated, resulting in empty data. My objective is: Retrieve all book ...

The useEffect function is not being executed

Seeking assistance from anyone willing to help. Thank you in advance. While working on a project, I encountered an issue. My useEffect function is not being called as expected. Despite trying different dependencies, I have been unable to resolve the issue ...

What is the best way to handle a global variable in Vue.js?

I am facing an issue with a mobile webview where a global config object is being injected: Vue.prototype.$configServer = { MODE: "DEBUG", isMobile: false, injected: false, version: -1, title:"App", user: null, host: "http://127.0.0.1:8080" } ...

The port has not been defined

My Node server appears to be operational, however the console is displaying an error message stating that the port is undefined. const express = require('express'); const env = require('dotenv') const app = express(); env.config(); ap ...

Display hidden text upon clicking using React Material UI Typography

I have a situation where I need to display text in Typography rows, but if the text is too long to fit into 2 rows, ellipsis are displayed at the end. However, I would like to show the full text when the user clicks on the element. I am attempting to chang ...

Bootstrap Modal for WooCommerce

I'm facing an issue while trying to create a modal window using woocommerce variables ($product). The problem lies in the placement of my modal and accessing the correct product id. Here is the code snippet I've been working on. Unfortunately, i ...

Challenges faced during the implementation of a personalized transport system in Sentry

Struggling to set up a custom transport for my react app within a UWP container. The fetch API in the UWP environment isn't cooperating with sending events to Sentry, which I discovered after a lengthy debugging session. It appears that the fetch API ...

Having trouble with the functionality of the cascading menu?

I am having trouble with a drop-down menu. The first level works fine, but I can't seem to get the second level of the menu to display. Appreciate any help you can offer. Thank you. javascript <script type="text/javascript"> $(document).ready( ...

A step-by-step guide on making a web API request to propublica.org using an Angular service

Currently, I am attempting to extract data from propublica.org's congress api using an Angular 8 service. Despite being new to making Http calls to an external web api, I am facing challenges in comprehending the documentation available at this link: ...

generating a dynamic string array containing particular elements

Given a string "hello @steph the email you requested is [email protected] for user @test" The goal is to transform it into: ['hello ', <a href="">@steph</a>, 'the email you requested is <a href="/cdn-cgi/l/email-protect ...

Is it possible to use ref in React to reference various elements based on specific actions?

I'm having trouble targeting the clicked button using a ref as I always get the second one. Any ideas on how to solve this issue? Also, if I have a native select element with two optgroups, is it possible to determine from which optgroup the selection ...

Utilizing ReactJS to display a new screen post-login using a form, extracting information from Express JSON

I am facing a challenge with updating the page on my SPA application after a successful login. I have successfully sent the form data to the API using a proxy, but now the API responds with a user_ID in JSON format. However, I'm struggling with making ...

Determine the output based on the data received from the ajax post request

I am seeking a way to validate my form based on the data returned. Currently, the validation only returns false if the entire post function is false. Is there a solution to differentiate how it is returned depending on which condition is met? This is my ...