Unable to receive URL parameters using JavaScript on a mobile device

I have been developing a program that displays all users' buttons on a screen, except for the current user's buttons. I came across this code snippet to extract URL parameters:

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return "";
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

My program successfully adds buttons to all players' screens, but there seems to be an issue with the parameter extraction code on my iPhone and iPad compared to my computer. The URL parameters in question are formatted as: ?username=User1 On my computer, when I execute getParameterByName('username'), it correctly returns User1. However, on mobile devices, it simply returns null. Any insights or suggestions on how to troubleshoot this?

Answer №1

This script is a handy JavaScript function I created for extracting URL parameters. It returns an associative array of values, allowing you to request specific values as needed.

// demonstration function
console.clear();
document.querySelector(".btn").addEventListener("click", function () {
  console.log('username:', getUrlParams("username"));
  console.log('all-params', getUrlParams());
});

// Function to retrieve URL parameters
getUrlParams = function (key) {
  var paramsArray = [],
    urlParams = window.location.href
      .slice(window.location.href.indexOf("?") + 1)
      .split("&");
  urlParams.every(function (param) {
    var keyValue = param.split("="),
      tempObj = {};
    if (keyValue.length === 2) {
      tempObj[keyValue[0]] = keyValue[1];
      if (key && key === keyValue[0]) {
        paramsArray = keyValue[1];
        return false;
      }
      paramsArray.push(tempObj);
    }
  });
  return paramsArray.length > 0 ? (key && paramsArray[0] === key ? paramsArray[1] : paramsArray) : undefined;
};
<button class="btn">Click me</button>

[EDIT] In this code snippet, both calls will return "undefined" because there are no URL parameters in the URL provided. You can try running the code on this CodePen instead (check your web console): https://codepen.io/cjboco/pen/MWwZbKO?editors=1010

[EDIT#2] Here's an example of the expected results:

Call: getURLParams("username")
Result: "User1"

Call: getURLParams()
Result: [{"username","User1"}]

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

Using Javascript to update text content by utilizing `innerText` property instead of checking if it is

How can I selectively use Javascript to replace the specific word "Rindan" in the text below, but not if it appears within an attribute such as img alt=="Rindan"? I only want to replace instances of the word "Rindans" when it is part of the inner text an ...

Retrieve the Latest Information from the Asp.Table

My table setup is as follows: <asp:Table ID="model" runat='server'> <asp:TableRow> <asp:TableHeaderCell class="col-xs-2"> Name </asp:TableHeaderCell> <asp:TableHeaderCell class="col- ...

Keep verifying the boolean value repeatedly

I've been working on implementing infinite scroll functionality for my card elements. Within my data.service file, I have a variable called reload that is utilized to determine whether more data needs to be loaded. This variable is set to true when th ...

Refresh a div with Ajax once all data has been fully loaded

I am currently using an ajax refresh div function that reloads a specific div every 10 seconds. Occasionally, the div loads before receiving data from mysql. Is there a way to modify it so that it waits 2 seconds after reloading the div? <script type ...

"An error occurred with the Google chart due to 'null' not being recognized as an object, specifically in relation to the select menu and onchange event

Currently, I have implemented the following Script: <header> <script type="text/javascript" src="http://www.google.com/jsapi"></script> </header> <body> <script type="text/javascript"> google.load("visualization", "1 ...

Dealing with Array Splicing Issues in Angular

Being fairly new to the world of AngularJS, I suspect that I am just making a simple mistake. My goal is to splice the cardTypes array at the var newCard = cardTypes.shift(); line rather than using .shift() so that I can consider my ng-repeat index. Whil ...

What setting should I adjust in order to modify the color in question?

Looking to Customize Radar Chart Highlighted Line Colors https://i.sstatic.net/PqWc4.png I am currently working on a Radar Chart and I am trying to figure out which property needs to be edited in order to change the color of the highlighted lines. I have ...

The property 'createUploadWidget' cannot be read from an undefined source

While working on a React js tutorial, I encountered an issue related to using Cloudinary React SDK for image and video uploads. Specifically, I was using the Upload Widget provided by Cloudinary and faced an error when trying to open the widget - 'Typ ...

Mastering Backbone views and router functionality is essential for building scalable and efficient web

In my code, I have a series of page states that mimic the steps of a shopping cart checkout process. The first set of code sets up the ItemsCollection, ItemsView, and ItemsApp in Backbone.js. var ItemsCollection = Backbone.Collection.extend({ model: I ...

Is it possible to transmit messages from a Chrome extension to a Java server?

My question is, if I want to create a Chrome extension that sends messages to a Java server, should I use the XmlHttpRequest API in the extension and have the Java server as an HTTP server? ...

What is the best way to store data retrieved using a model.find({}) operation?

I am currently attempting to calculate the average value of a collection in my database using Mongoose and Express. The objective is to utilize this calculated value on the "calculator" page when rendering, which is why it is embedded in a post for that sp ...

Preventing Users from Uploading Anything Other than PDFs with Vue

I am currently working with Bootstrap-Vue and Vue2. Utilizing the Form File Input, I want to enable users to upload files, but specifically in PDF format. To achieve this, I have included accept="application/pdf": <b-form-file v-model=&quo ...

NPM encountered difficulties in resolving the dependency tree

I seem to be encountering a persistent issue that I cannot resolve on my own. My attempt to update webpack and webpack-cli in a project has been met with repeated errors of this nature: npm install webpack@latest --save-dev npm ERR! code ERESOLVE npm E ...

Exploring the nuances between Ruby on Rails and the responses from json and JavaScript ajax

I am interested in learning the most effective method for handling an ajax request. Would it be better to send json data and parse it on the client side (for instance using pure), or should I generate javascript at the server side and send back the respo ...

The navigation bar does not display the CSS when in the active state

I created a navigation bar in ReactJS and I need the tabs to stay highlighted when clicked, but the styles are not applying correctly. I have double-checked that the stylesheet is linked properly based on the Reactjs file structure. For reference, I used ...

What could be causing XMLHttpRequest to encounter issues with the readystate and status states while running on localhost

Hey guys, I'm having some trouble with this code and can't figure out why it's not working. Here is the code snippet: <script> function findMatch() { if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); ...

How to Extract a URL from an Anchor Tag without an HREF Attribute Using Selenium

How can I make a link, which normally opens in a new window when clicked, open in the current window instead? The link does not have an href attribute, only an id and a class. For example: <a id="thisLink" class="linkOut">someLinkText</a> I r ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

Dynamic font size that adjusts as you change the window dimensions

Is there a way to adjust the font size in HTML so that when I resize the window, the text size adjusts accordingly? It's like setting a percentage for the text based on the size of the container it is in. Let me provide an example of what I have in m ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...