Is it possible to disable redirection in Javascript?

I have included the following script in the head section of my webpage:

<script type="text/javascript">

if (screen.width <= 800) {
    window.location = "http://m.domain.com";
}

</script>

On the mobile version of my site, I have a button labeled "Main Site". How can I make it so that when users click on this button, they are directed to my main site without being redirected back to the mobile version?

Additionally, I want users to be taken to the main site only once. After that, if they revisit the website, I would like them to land on the mobile version.

Answer №1

To easily direct users to your main site, simply link the main site to a visible button. For added functionality, consider using a URL parameter to enforce the main layout. This can be achieved by implementing:

<a href="http://www.domain.com?forcelayout=main">Main site</a>

Check for the specified parameter in order to activate the main layout override. Alternatively, the current script being utilized will automatically handle this process.


Utilize the below function to extract query string information. [Source]

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

Subsequently, integrate this within your logic as exemplified below:

if (screen.width <= 800 && getParameterByName('forceLayout') != 'main') {
    window.location = "http://m.domain.com";
}

Answer №2

One way to check the referring document is by using document.referrer

<script type="text/javascript>
if (screen.width <= 800 && document.referrer.indexOf('http://m.domain.com') != 0) {
    window.location = "http://m.domain.com";
}
</script>

Answer №3

Prior to redirecting someone to your primary website after clicking the "Main site" button, generate a "MobilOptOut" cookie and subsequently check for its existence within an if statement that evaluates screen width.

Answer №4

To maintain the current view of the user, the client must handle state management effectively as HTTP is a stateless protocol. One approach is to use cookies to store and retrieve the user's selection across different requests.

When the user triggers the main version display by clicking a button, the cookie storing the preference should be deleted. Conversely, when the user selects the mobile version, the cookie should be set accordingly. Handling cookie manipulation in JavaScript may require specific libraries, so below is pseudocode demonstrating how your webpage could manage this functionality.

// Pseudocode:
// Sets a cookie named "view" with the value "mobile"
function setMobileView() {
    Cookie.set("view", "mobile");
}
mobileViewButton.onclick = setMobileView;

// Deletes the cookie named "view"
function setMainView() {
    Cookie.delete("view");
}
mainViewButton.onclick = setMainView;

Below is pseudocode illustrating how the redirection logic could determine which view to display:

// Pseudocode for determining the view to display
if (view === "mobile") {
  location.href = "http://m.domain.com";
}

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

Where should the JWT token be placed in the browser header and what additional information needs to be included?

I recently started learning backend development and decided to work on creating an authentication and authorization API. While testing the app in Postman, I noticed that I had to manually send the token and wanted to automate this process by sending it to ...

Issue: It is not possible to display a <Router> within another <Router>. It is important to only have one router in your application

An error is occurring in my React application because I have nested routers. I need to use a second router in Navbar.js for the <Link> component to work. Currently, I have React Router implemented in two different files, and if I remove one of them, ...

Tips for changing a specific item within an ng-repeat loop in AngularJS

Here is my HTML code: <tr ng-repeat="customer in customers"> <td> {{customer.customer_name}} </td> <td> {{customer.mobile}} </td> </tr> Upon executing this code, I receive 3 <tr>...</tr> blocks as s ...

Using hooks to call a function in a different function is not allowed

The log out feature allows a user to sign out by initiating an API request and removing the user's data from LocalStorage and the Redux store. To achieve this, the function utilizes two hooks: useDispatch and useFetch (a custom hook). import {useDispa ...

What impact does Bootstrap .ratio have in making the img show up over the offcanvas menu?

Is there a way to prevent a ratioed image from appearing above the offcanvas menu? When using Bootstrap 5 and specifying a 16x9 ratio for the image... <div class="ratio ratio-16x9 my-3"> <img width="768" height=&q ...

Establishing a pre-selected option in a drop-down menu

I am working on a dropdown list and my goal is to have the default option selected when the page loads <b>Filter Within Months:</b> <select class="btn green" ng-model="myOptions" ng-options="i.label for i in items track by i.id" ng-change= ...

Immediately redirected to the index page without undergoing login validation

After attempting to create a login page, I encountered an issue where upon entering information into the text fields and clicking the login button, the page automatically redirects to the index page instead of displaying an error message for incorrect user ...

Creating intricate sketches on multiple canvas elements using jQuery

When making an Ajax request, I am trying to draw the elements on multiple canvas elements. However, all images are only being drawn on the first canvas element. How can I target each canvas element individually in the success function to draw the image? ...

Tips for transferring state between functions and classes in reactjs

I'm currently utilizing hooks and have a function that makes use of the dropzone library: export function UploadFile() { const [files] = useState([]); return ( <MaterialDropZone files={files} sh ...

Generate a hyperlink within a paragraph

Can anyone provide tips on how to turn a string from Json into a paragraph with a hyperlink included? <p>Dumy Dumy Dumy Dumy Dumy Dumy Dumy DumyDumyDumyDumy abc.com </p> Currently, the paragraph displays as is, but I would like to make abc.c ...

Struggling with CSS layout: Organizing and nesting divs

I am striving to create a layout like the one shown here: https://i.sstatic.net/LInER.jpg Presented below is my current HTML structure: <div id="main"> <div id="content1"> <span>Content1</span> <div id="text ...

What is the reason for utilizing style-loader as a backup option alongside Webpack's ExtractSass plugin?

Here is an example where style-loader is being used as a fallback in development mode. But why is it used this way? You can find more details here. const ExtractTextPlugin = require("extract-text-webpack-plugin"); const extractSass = new ExtractTextPlu ...

Fetching data using JSONRequest sample code

I am new to web development and this is my first attempt at using JSON. On the JSON website (http://www.json.org/JSONRequest.html), they recommend using JSONRequest.get for certain tasks. However, I keep running into an error stating "JSONRequest is not ...

Tips for creating text that adjusts to different screen sizes within a div

I am trying to ensure that the height on the left side matches the height on the right, so it's important that it looks good on various devices like tablets, PCs, etc. However, when I resize my browser window, the video on the right side shrinks while ...

Passing conditional empty variables through `res.render`

I am currently facing a challenge with passing multiple variables into a res.render. One of the variables will have an object to send through, while the other may not have anything to pass. As a result, I am encountering an undefined error. Below is the ...

Tips on retaining the value of $index in ng-repeat and storing it within the array

I currently have a cart for shopping. The code for the "add to cart" function looks something like this (shortened): "add" : function(code) { codes.push({ "id" : code.id, "order" : "N/A", ...

Chutzpah - unable to locate variable: module

I recently installed Chutzpah in order to execute Jasmine-based unit tests for Javascript. This is my first experience with both Jasmine, Chutzpah, and Angular. I have created a test file for an angular filter called filters.spec.js which contains the cod ...

What could be causing my canvas to not display my sprite?

Currently, I am in the process of learning JavaScript and experimenting with creating games to make the learning experience more enjoyable. However, I am facing an issue while using EaselJS and CreateJS to develop these games as a beginner. I need some as ...

What is preventing my overlay from covering the bootstrap navigation bar?

I'm working on implementing an overlay feature in my project to prevent users from interacting before the content is fully loaded. I have included the following overlay code: .overlay { opacity: 0.5; background: #000; width: 100%; height: 1 ...