Checking and rectifying website addresses with JavaScript

Summary: User inputs a short-form/alias URL into a field (website.com). I need to identify the full URL and replace the input with it (which could be www.website.com or www2.website.com based on redirection).

--

My web service allows users to input URLs. Upon submission, my service sends GET/POST requests to that URL from the server and processes the data received.

The issue arises when users enter short-form URLs like washingtonpost.com instead of the complete https://www.washingtonpost.com. While browsers handle this by automatically following the redirect, managing this logic on the server end is complex and I'd prefer to avoid it.

I am seeking a way to "validate" the entered URL. One approach is to add www to all URLs without it, but not all websites follow that convention. Some use www2, while others omit it entirely. The most reliable method seems to be listening for redirects and extracting the location value from the response.

One idea involves using JavaScript to validate the URL by sending a GET request, analyzing the response for a redirect status code (301, 302, etc.), and replacing the input with the final destination URL.

The challenge here is CORS. This results in an error in the console:

XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.`

What would be the optimal approach to solve this? Preferably with JavaScript.

Answer №1

It is not feasible to achieve this task using Javascript due to the security restrictions it imposes in such scenarios.

One workaround is to create an iframe and load the URL, but when dealing with cross-domain redirects, the iframe may restrict access to its location.href.

Alternatively, you can attempt to make AJAX requests, but this method requires the target server to have CORS enabled, which may not be possible if users are allowed to input any URL.

In essence, the solution you seek would violate the cross-domain security policies of browsers, so it might be better to perform this check on the backend.


If backend implementation is not an option:

Fortunately, there are proxy servers available that support CORS and offer their services for reuse. You can utilize their services as long as no sensitive data is exposed. An example includes using a service like cors-anywhere and accessing the custom final URL provided in their header (X-Final-Url). Just remember to specify the protocol (http/https) in the URL.

$.ajaxPrefilter( function (options) {
  if (options.crossDomain && jQuery.support.cors) {
    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
    options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
    //options.url = "http://cors.corsproxy.io/url=" + options.url;
  }
});

 $.ajax({
   type: 'HEAD', //'GET'
   url:'http://washingtonpost.com',
   success: function(data, textStatus, request){
        console.log(request.getResponseHeader('X-Final-Url'));
   },
   error: function (request, textStatus, errorThrown) {
        console.log(request.getResponseHeader('X-Final-Url'));
   }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Choosing the right framework for implementing push notifications can be a critical decision. Should

I am currently working on a Java application that requires the server to send push notifications to the client every one second. To achieve this, I am using HTML5 server-sent events for one-way communication from the server to the client. However, my conce ...

Can you provide guidance on implementing StyledComponents within the app folder of Next.js version 13?

Quoting information from the Next.js documentation: Attention: CSS-in-JS libraries that rely on runtime JavaScript are currently not compatible with Server Components. The following libraries are supported in Client Components within the app directory: s ...

Instructions for creating a scrollable unordered list when it reaches its maximum capacity

My HTML code has a <ul> element with the following structure: <ul id="messages"> </ul> In my HTML file, I have not specified any <li> items. However, in my JavaScript code using jQuery, I dynamically add <li> items to the & ...

What could be causing my cmd to report an error stating that it is unable to locate the node-modules

https://i.sstatic.net/4ztfB.png Take a look at my command prompt below. Do I need to keep the module folder and the code folder in the same directory? ...

The parameters remain consistent across all Angular directives

I have created a directive called 'filterComponent' with the following code: app.directive('filterComponent', function() { return { restrict: 'E', templateUrl: 'filter-component.html', link: function ...

Transmitting chosen option using AJAX and JavaScript

I have a select dropdown that I want to use to send a selected option to AJAX and then display it. Here is my HTML: <label>Tag</label> <select id="day"></select> <label>Monat</label> <select id="month"&g ...

The use of jquery UI.js is causing issues with loading select menus dynamically

When attempting to load a dynamically loaded select menu on my page using Ajax/PHP, I encountered an issue where the jquery UI plugin prevented the data from loading. As a result, I was unable to see anything when changing the first select menu. Below is ...

Trouble with Mongoose save() function failing to update data

I am currently working on enhancing a fully functioning CRUD app by adding a new feature that allows users to update a list of vendors. They have the ability to add new vendors, update existing ones, and delete vendors. While the add and delete functions a ...

Redirecting pages without a hash portion

In my Express.js app.js file, there is a get route that looks like this: app.get('/admin', function(req, res, next){ if(req.isAuthenticated()) { return next(); } res.redirect('/admin/login'); },Routes.Admin.Index); When a ...

Using React for form validation

I'm facing a challenge while trying to develop a user registration form, especially when it comes to displaying form validation errors. Issues: 1) The input fails to post (via axios) to the database upon submission for inputs without errors. 2) The e ...

Creating a personalized scrollbar for the body using Bootstrap 3

I've been searching for the best solution to customize the scroll-bar in Bootstrap, but I haven't found anything that works perfectly yet. I want to replace the default browser scroll-bar on the body and other elements like panels, wells, and tex ...

Utilize AJAX response to mark checkbox as checked

I have an HTML checkbox that I am attempting to check using a script received as an ajax response. Below is my HTML snippet: <form class="form-vertical sms-settings-form"> <div class="form-group"> <div data-toggle="tooltip" titl ...

Challenge with executing javascript library (photo sphere viewer)

I was excited to incorporate Photo Sphere Viewer into my project. After running npm i photo-sphere-viewer I noticed that the modules were successfully downloaded. Following that, I added this line inside my project: import PhotoSphereViewer from ' ...

Transition smoothly between two images with CSS or jQuery

I am working on a project where I need to implement a hover effect that fades in a second image above the initial image. The challenge is to ensure that the second image remains hidden initially and smoothly fades in without causing the initial image to fa ...

Switch to display only when selected

When I click on the details link, it will show all information. However, what I actually want is for it to toggle only the specific detail that I clicked on. Check out this example fiddle Here is the JavaScript code: $('.listt ul').hide(); $( ...

How to dynamically display content based on option selection in AngularJS using ng-show

I am trying to create a functionality where my input field is bound to my select option. When the select option is set to Yes, I want the input field to be visible, and when it's set to No, I want the input field to be hidden. (function(){ var app ...

Running a function on a specific route within the same file in Node.js - here's how to do it

I am looking to execute a function on a specific route that is defined within the same file. module.exports.controller = function(app) { app.get('/folders/create', createDirectory); } var createDirectory = function(path, name, permissions, v ...

Enhancing JSON Objects in AngularJS with Custom Properties and Calculations

Hello, I'm still getting the hang of angularjs and could use some guidance. I have a Rest service that provides data on saleItems when a get request is made, as shown below: saleItems = [ { "id": 236, "variant": "Oval Holder", "mrp": "6 ...

Using Angular to retrieve data from a JSON file correlating with information in another JSON file

Just starting out with angular and facing a problem where I'm unsure of the best approach to setting up this code efficiently. I have 2 JSON files: images.json { "imageName": "example.jpg", "imageTags": ["fun","work","utility" ...

Guide for running an await function consecutively with JavaScript and React

I have the following code snippet: const somePromises = values.map(({variable, value}) => this.post('/api/values/', { variable, value, item: itemId, }) ); await Promise.all(somePromises); if (somecondition) { ...