Using Jquery to Redirect Users According to URL Position

My current dilemma involves...

  1. I want to create a condition where if the URL specifically contains /foldername/index.htm or /foldername/ on mydomain.com, then it should redirect to http://www.example.com
  2. If the URL includes any URL parameter with /foldername/index.htm?example, there should be no redirection
  3. All other URLs should not trigger a redirect

Below is my incomplete JavaScript code which I am working on in order to address this issue...

var loc = ""+window.location;
if (loc.indexOf("mydomain.com") >= 0) {
    var allowedUrls = ["/foldername/index.htm", "/foldername/"];
    window.location = "http://www.example.com"; 
}

The goal of this script is to manage traffic coming to a specific URL that some users have bookmarked. We want to track the number of visits before deciding on further actions regarding the page.

Answer №1

Isn't it true that the page will always remain on the same domain? Additionally, if the URL contains /foldername/pagename.htm, wouldn't it already include /foldername? Therefore, an && check there would be unnecessary.

Give this code a try.

var path = window.location.pathname;

if  ( (path === '/foldername' || path === '/foldername/index.html') && !window.location.search ) {
    alert('should redirect');
} else {
    alert('should not redirect');
}

Answer №2

let currentUrl = window.location;
let domainPattern = /mywebsite\.com\/[a-zA-Z0-9_\-]*\/[a-zA-Z0-9_\-]*[\/\.a-z]*$/    
if(domainPattern.test(currentUrl)) { 
  window.location = "http://www.samplewebsite.com"; 
}

Answer №3

Learn about the window.location object which offers attributes like pathname, search, and hostname, saving you from dealing with regular expressions (which you would likely mess up anyway). Consider implementing something similar to this:

// no redirect needed if there is a query string
var redirect = !window.location.search 
  // only redirect if this script is running on mydomain.com or its sub-domains
  && window.location.hostname.match(/(?:^|\.)mydomain\.com$/)
  // only redirect if the path is /foldername/ or /foldername/index.html
  && (window.location.pathname === '/foldername/' || window.location.pathname === '/foldername/index.html');

if (redirect) {
  alert('success');
}

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

Adjust the svg rate using jQuery or JavaScript

Seeking help with a gauge I found on CodePen - struggling to adjust bubble values... <path id="Fill-13" fill="#F8B50F" d="M3.7 88.532h26.535v-#.795H3.7z"/> Can change the bars in JS, but not the bubbles using jq/js. Adjust the gauge with values be ...

Fixing an erroneous value that has been dragged into the drop function with Jquery

I am encountering an issue with my codes and need some assistance in identifying the problem. The data is being dynamically loaded from the database, and I am using a foreach loop to display all items in a draggable div. The issue arises when I drag an it ...

Turn off HTML5 Audio

There are 4 <audio> elements on a webpage. The client has asked for them to be available sequentially. Meaning, the first audio should play, then the rest should remain disabled until the first one finishes, and so on. In addition, they want the au ...

Use either lodash or a for loop to organize a group of JSON objects

Here is the array I am working with: [ { corequisite: "", curriculumYr: "2017-2018", programCode: "ET" majorCode: "AET", prerequisites: "GMRC 101||Math 101" semester: "1st Term", year: "1st Year", subjectCode : "ENG ...

It is not possible to use Date.now within passport.js

When creating a user via Facebook on my Node.js website using passport, I want to assign the register date. In my Mongoose Schema, I can use the following for the local provider: regisDate: { type: Date, default: Date.now }, However, when it co ...

Transforming the Date into Local Time: An Instantaneous Process?

I am currently working with a Kendo UI MVC grid that contains three date columns. These dates, which do not include any time values, are stored in the database as local time rather than UTC. The columns within the grid are defined like so: col ...

Unexpected token < error encountered during parsing in jQuery Ajax long polling append

How can I create a real-time ticker similar to Facebook using Jquery Ajax long poll and PHP? I encountered an error in my script that displays "error parsererror (SyntaxError: Unexpected token <)". What could be causing this error in my code? Here is ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

Modify the height of React Cards without implementing collapse functionality

Currently, I am in the process of developing a web interface that displays various processes and services. The information is presented in React cards that support expand/collapse functionality. However, I am facing an issue where expanding one card affect ...

Creating a custom dialog box using JavaScript

How can I create a customized dialog box in the center without displaying "the host name says..." using CSS? function myFunction() { alert("Record Save"); } Thank you in advance! ...

Ways to effectively handle diverse Angular module dependencies

Although I am still new to Angular, I have been striving to write more modular code and rely less on cramming logic into the controller. Instead, I have been utilizing independent services. However, a recurring issue I am facing is having to re-declare the ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...

Triggering an Ajax call for form validation only occurs when the form is not validated

I am struggling with a simple form that has an Ajax call, but the ajax call gets executed even if the form is not validated. In the code snippet below, the line console.log("This line should execute only if Form is validated"); gets executed when the form ...

Eliminate redundant sets of comma-separated numbers from the jQuery input text value

On my webpage, there is an input with a value that looks like this: 1,7,1,4,22,58,58,1,1,4,7 <input type="text" name="hello" id="thankyouforhelping" value="" aria-invalid="false"> I have attempted mu ...

Using Nestjs to inject providers into new instances of objects created using the "new" keyword

Is it possible to inject a provider into objects created by using the new keyword? For instance: @Injectable() export class SomeService { } export class SomeObject { @Inject() service: SomeService; } let obj = new SomeObject(); When I try this in my t ...

Managing various encoding methods when retrieving the XML data feed

I'm attempting to access the feed from the following URL: http://www.chinanews.com/rss/scroll-news.xml using the request module. However, the content I receive appears garbled with characters like ʷ)(й)޹. Upon inspecting the XML, I noticed that ...

Execute the second method once the first method has completed its execution

As I develop my npm package, I am faced with the challenge of ensuring that one method waits for another to complete before executing. For example: var package = require('myNpmPackage'); package.method1(options); ... Later on, possibly in a dif ...

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

How can I adjust the height of an iframe dynamically using AngularJS?

I wrote a function that resizes the height of an iframe element to always be 100% after it loads: app.directive('iframeAutoSize', [function() { return { restrict: 'A', link: function(scope, element, attrs) { ...

What is the downside of exporting all components into one index.js file?

My approach involves exporting all components to an index.js file, allowing me to easily import them into any other file with the code snippet below. This method is not only straightforward but also keeps my code cleaner. import { RocketCard, Container, Na ...