How to extract the root website URL using JavaScript for redirection purposes

I am facing an issue with redirecting to the Login page from every page on my website after session timeout. I attempted to set the window location to the login page using the following code:

var ParentUrl = encodeURIComponent(window.parent.location.href);
document.location.href = "/Login.aspx?ReturnUrl=" + ParentUrl;

However, I found that the use of "~" is not supported in this context. My Login page is located under the root folder of my website.

For example: *http://server/website/*Login.aspx

Is there a way to retrieve this URL using JavaScript?

Thank you,

Inbal.

Answer №1

If you want to retrieve the parent URL and then encode it, you can simply use window.location.origin. Once you have the parent URL encoded, you can easily append it to a login URL for redirection purposes.

var parentUrl = encodeURIComponent(window.location.href),
    loginUrl = window.location.origin + "/login.html?redirect=" + parentUrl;

window.location.href = loginUrl;

For consistent functionality across different browsers, it's advisable to utilize window.location as it is both readable and writable on all compliant browsers. On the other hand, document.location may be read-only on certain browsers like Internet Explorer.

Answer №2

function retrieveURL() { 
    var parts = window.location.href.split("/"); 
    delete parts[parts.length - 1]; 
    return parts.join("/"); 
}

This method can be implemented as follows:

document.location.href = retrieveURL() + "Login.appx?ReturnUrl=";

The distinction between my function and the initial response is that while a "/" will lead to server/page redirection, my code directs (in your provided URL example) to server/website/page.

Answer №3

Why do we need to use the tilde (~) symbol? Upon closer examination, it appears that removing it may resolve the issue. Consider the following revised code snippet:

document.location.href = "/Login.appx?ReturnUrl=" + ParentUrl;

[UPDATE] In response to the initial comment...

I propose a slight modification to the code that may resolve the issue:

function getLoginPage() {
    var urlParts = document.location.href.split("/");
    return "/" + urlParts[2] + "/" + urlParts[3] + "/Login.aspx";
}

document.location.href = getLoginPage() + "?ReturnUrl=" + ParentUrl;

Answer №4

It is important to note that the section "/website" contains server-side information that cannot be determined solely by JavaScript.

Therefore, it is necessary to transmit this information from the server to the client. One efficient way to achieve this is by passing the complete URL "http://server/website" in one go.

Answer №5

I adjusted the solution provided by PerKristian to suit my specific needs,

function fetchBaseUrl() {
    var regex = new RegExp(/^.*\/\/[^\/]+/);
    return regex.exec(window.location.href);
}

It captures everything until the first single /

For instance,

http://techblog.com/post/56236133/extract-root-url-in-js-for-navigation

will output http://techblog.com

Answer №6

This code snippet retrieves the root (base) URL from the current webpage.

Imagine you have a URL like this: http://www.example.com/something/index.html You desire to get: http://www.example.com/something/

function fetchRootUrl() {
    var re = new RegExp(/^.*\//);
    return re.exec(window.location.href);
}

For more information, check out: Javascript: Get base URL or root URL

Answer №7

My usual practice is to create a file named "settings.js" where I keep all the settings for my application. For instance:

settings = { "root": "myAppRoot/" /*, ... */ };

Then, in my script, I can make a call like this:

myDynamicDiv.load("/" + settings.root + "urlPart1/urlPart2/app"

Answer №8

function getHomePage(url) { 
    var newArray = url.replace('//','@@').split("/");
    return newArray[0].replace('@@','//');
}

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

React - error caused by an invalid hook call. Uncaught Error: React encountered a minified error with code #

My goal is to incorporate the micro-frontend concept by implementing various react apps. Container Header Dashboard All three are separate applications. I intend to utilize the Header and Dashboard apps within the Container app. For the Header app, it& ...

Employ the Google Charting library for creating a GeoChart that is currently not displaying

Hello everyone. I'm having a bit of an issue with my web page development. I've been trying to add a GeoChart, but no matter how many times I copy-paste the code from the Google developer's website, the map just won't show up. I must be ...

Determine the current whereabouts and actions of the specified user

I am in the process of developing a command for my Discord JS bot that, when activated, will fetch the current game (or status if no game) of the user mentioned in the command. Subsequently, the bot will send a message stating Mentioned User has been playi ...

JavaScript or jQuery can be used to rearrange the position of child divs within parent divs with a single action

I am facing a dilemma with 5 identical divs, each containing text and an image. My goal is to rearrange the child divs so that the text comes after the image in each article. Put simply, I want the image to be displayed above the text in all instances. Al ...

Please provide links to both the image and text within a Rails 3.1 application

Hey there! I have a small piece of code and I'm wondering how to add a link to both the icon and text. I am calling an icon from a class. Check out my code below: <td class="cv-class_<%= index + 1 %>"> <a onClick="ad ...

Retrieve the value of an object property within a function

I'm facing a bit of a challenge here and couldn't find a solution. Here's an illustration of the object I am working with: obj = { key1 : {val : "hi", val2 : "pizza"}, key2 : {val : "hello", val2 : "cheese"} ...

Interactive JavaScript Linkage

Recently, I came across some code that I inherited (definitely not mine!) which uses a session variable in the HTML header to link to a specific javascript file. For example: <SCRIPT language="javascript" src="../JavaScript/<%=Session("jsFileName") ...

The chart is failing to update with the data it obtained through Jquery

Scenario: I want to populate a chart using data fetched by Jquery. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=test_data; ...

Preventing access to websites through a web application using JavaScript

I am in the process of creating a web application that enables users to create a list of websites they wish to block, preventing access from their browsers. My goal is to block websites on all browsers, but I have narrowed my focus to Chrome for now. I ha ...

What is the best way to determine when all asynchronous tasks and callbacks have been completed so that we can proceed securely?

Here is a code snippet that reads a file containing documents sorted by categories and values in descending order. It then modifies the documents with the highest value for each category. Below is the code: var MongoClient = require('mongodb'). ...

What is the correct way to initialize a variable that will store the output of setInterval?

While examining a question, I came across someone's solution that proposed updating the code below. In the comments section, it was suggested: Instead of setting this.tm to undefined, we should set it to 0. Since it's a time interval, it shoul ...

What signals to Angular that $httpBackend is substituting $http during the testing of AngularJS?

My factory, called myFactory, has a dependency on $http. When writing tests for this, I needed to mock this dependency. After some research, I discovered that I could accomplish this using $httpBackend. Implementing the code below successfully achieved t ...

There is an issue with Nuxt 3 layers not functioning properly when trying to access a project page from a different

Is there a way to make a project function independently while still being accessible through layers and able to run smoothly? The current project structure is as follows: ...

Ways to retrieve the child number using JavaScript or PHP

Is there a way to retrieve the child number upon clicking? View screenshot For example, when I click on the X button, I want to remove that specific element. However, this action should only apply to item n2. In order to achieve this, I need to determine ...

Step-by-step guide on transferring an HTML5 sqlite result set to a server using AJAX

Imagine I have a scenario where I receive a result set as shown below: db.transaction( function(transaction) { transaction.executeSql( 'SELECT col1, col2, col3 FROM table;', [],function(transaction, result){ //need to find a ...

What is causing ngResource to change the saved object to something like "g {0: "O", 1: "K", ..} once it receives a response?

In my current setup, I have a default ngResource that is defined in the following way: var Posts = $resource('/posts/'); Once I retrieve a blog post from my nodejs server using the code below: $scope.post = Posts.get({_id:query._id}); The use ...

Discover the underlying data within a nested JSON structure and track back to identify the corresponding values

In the JSON structure provided below, Suppose I have the chapter "number" and section "number". What is the most efficient way to search and trace backwards starting from what I already know, in order to find the "number" of the title within titles and t ...

Positioning an element in the center of another using JQuery

Greetings! I am currently working with some elements that look like this: <div id="one">content</div> <div id="two">content</div> These elements are followed by another set of elements (without any parent, placed directly after th ...

Using Socket.IO in Node.js to distribute information to every connected client

Currently, I am in the process of developing a WebGL multiplayer game. My approach involves using socket.io and express in node.js to enable multiplayer functionality. However, I am encountering an issue with broadcasting key events. When a user presses a ...

Unable to set a JSON data as a value for a JavaScript variable

I am currently developing a YT mp3 downloader using the API provided by youtubeinmp3. I have been successful in obtaining the download link in JSON format. https://i.stack.imgur.com/3mxF2.png To assign the value of "link" from the JSON to a JavaScript va ...