What are some methods for substituting standard JavaScript built-in objects?

My client has developed their own app using Chromium, with a navigator.appVersion of AppleWebkit/534+

https://i.sstatic.net/zEZy6.jpg

To my surprise, they have replaced the standard JavaScript built-in objects with their own version. For instance, take a look at their custom Map implementation below:

Their Map object includes methods like:

arr:Array[0]
isEmpty:function
remove:function

However, it lacks the standard Map methods such as has, keys, and values. You can compare it to the standard Map object documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map (By the way, we require a Map object here instead of a plain JavaScript object because we need the keys to be something other than strings)

I am intrigued by how they managed to achieve this. What could be the reason behind such customization?

And more importantly, how can I revert back to the default built-in version?

https://i.sstatic.net/8PTkA.jpg

Answer №1

I encountered a similar issue where the global function was being overwritten.

One way I found to retrieve the original function is by utilizing the contentWindow property of an iframe:

While the following code may not execute properly in StackOverflow's code-snippets due to iframe policy, it should work in your own environment:

// contaminated Map
Map = function() {
    this.foo = 'bar';
}
const map1 = new Map();
console.log(map1);

// restoring Map
const iframe = document.createElement('iframe');
document.body.append(iframe);
const OriginalMap = iframe.contentWindow.Map;
iframe.remove();

const map2 = new OriginalMap();
map2.set('foo', 'bar');
console.log(map2);

A screenshot demonstrating its functionality can be viewed here:

https://i.sstatic.net/8dXc1.png

This solution acts as more of a workaround; I am uncertain if there exists a more optimal approach.

Answer №2

How was that accomplished?

It's actually quite simple:

Map = function() { ... }

Why would someone choose to do that?

As previously mentioned, it is likely because the code predates the availability of the built-in Map. If the code needs to be compatible with older browsers, then this decision may still hold relevance.

How can I revert back to using the built-in version?

The suggestion in another response is worth considering... I cannot think of a better approach myself.

However: It seems like your objective is to make modifications or extensions to an existing codebase. Having two separate Maps within the same code could lead to confusion -- for both yourself and future developers working on the project. As an alternative, I propose the following options:

  • Upgrade the entire system to utilize built-in JavaScript Maps. Replace all instances of the customized Map and then remove its definition. Use the built-in Map throughout the codebase. (Ensure client approval before dedicating time to this task.)
  • Maintain the current setup and continue utilizing the custom Map in your new code. While its methods may have different names, it appears to offer similar functionalities. You should be able to find examples of how to iterate over this type of map. (Keep the first option as a potential future consideration.)

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

Tinymce removes <html> tags from the output displayed in a textarea

I have created my own small CMS using Tinymce. When I insert plain text in pre tags, the code displays correctly on the website. However, when I update the editor, the HTML tags are removed. My Tinymce setup: <script type="text/javascript"> tinyMCE ...

Retrieve the callback arguments using sinon.spy within a JavaScript promise

During my test with mocha and sinon, I encountered an issue where I couldn't retrieve a callback value from inside a promise scope of an HTTP-request due to the asynchronous nature of promises. It seems that by the time sinon.spy checks on the callbac ...

Creating an event within a class that is generated dynamically when hovering

I'm trying to create a hover effect where an image moves around the page in a pattern (top left corner -> top right corner -> bottom right corner -> bottom left corner -> then back up to the top left corner). To achieve this, I am adding ...

Having issues with validating a form using Yup for a Checkbox input?

My form is built using mui, formik, and yup. If the input fields are empty (e.g. "surname") after clicking the submit button, an error is displayed. However, the issue arises when the checkbox for Terms of Service isn't checked as no error shows up. ...

"Error 404 encountered while trying to make an Ajax POST request

I am currently working on sending a test email using node.js. Here is a snippet of my server code in index.js: var http = require("http"), express = require('express'), nodemailer = require('nodemailer'), bodyParser = re ...

Customizing the styling of buttons in Highcharts is disabled when in full screen mode

I've integrated highcharts into my Angular application and included a custom button inside the chart to navigate users to another page. However, I encountered an issue when trying to fullscreen the chart using the export menu. The position of the cus ...

Go to a different page section using MUI 5

I am currently working on a React application and I want to implement a functionality where pressing a button on my Nav Bar will navigate to a specific section on the first page. To achieve this, I have created an onClick function for my button: const onNa ...

To achieve the desired format, where should I press or manipulate the information?

I need help with manipulating arrays to generate a specific JSON file structure. I've made some progress but got stuck at this point: var T_nn_IN = document.getElementById('datatablenewname'); var tabledata_newname_initialname = []; ...

When the collapsed navbar is displayed, elements are pushed beyond the boundaries of their parent container (Bootstrap 5)

Introduction Utilizing Bootstrap 5 (included with webpack 5), I am implementing the grid system and collapse function to design the homepage of this website, featuring 2 sidebars that collapse into a top bar. On mobile devices, the navigation collapses a ...

What is the best way to remove an item from my online shopping cart using JavaScript?

I am currently developing an online store website. One issue I am facing is deleting items from the cart after a customer completes an order. Below is the array of cart items: const products = [ { id: '0', name: 'Nike Slim Shirt&ap ...

How to safely add multiple objects to an array in TypeScript & React without replacing existing objects - Creating a Favorites list

I'm in the final stages of developing a weather application using TypeScipt and React. The last feature I need to implement is the ability for users to add queried locations to a favorites list, accessed through the "favorites" page. By clicking on a ...

What is the accurate way to write the ID selector for the select-option-selected in JQuery?

When it comes to extracting a value from a Select-Option using jQuery, the following syntax can be used. I have successfully retrieved data using this method. $( "#Vienna\\.rail0\\.track option:selected" ).text() However, there is an ...

Toggle visibility of table row upon user click (HTML/JQuery)

Having an issue with showing or hiding table rows using jQuery. I would like it so that when a user clicks on a table row with id="jobtitle", the corresponding tr with class="texter" will either show up or hide if it is already displayed. This is my curre ...

Securing data in the browser using JavaScript encryption and decrypting on the server side using Node.js

After hours of trying to encrypt a message using AES256 in the browser, send it to the server, and then decrypt it, I keep encountering this server-side error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt Despite using crypto- ...

CORS error: The 'Access-Control-Allow-Origin' header is missing

I have a website that is being accessed through multiple domain names. Let's say the main hosted website is example.com and the forwarded domain names are example-x.com, example-y.com, example-z.com When visitors access the forwarded domains, there ...

Tips for incorporating animated features into a bar graph using jQuery

How can I create a dynamic animated bar graph using jQuery? I am looking to make the bar slide up from the bottom, incorporating images for both the bar and background. I have already set the positioning in CSS and now need to add animation to make the bar ...

Cleaning up objects from memory in JavaScript following an AJAX request

I am developing a web application with dynamic content loading. In my code, I have a main container div (<div id="container"/>) where I use AJAX to load HTML content. // function overwritten by loadMenu functions // called before loading a new sect ...

Finding a way to extract a singular text node after the Span element but before the br tag using Selenium WebDriver

I am trying to retrieve the text between span and br tags. In the HTML snippet below, I am aiming to extract the Orange text: <td role="grid cell"> <span class="ui-column-title">Fruits</span> <span id="all fruits"> "Orange" < ...

Developing a personalized Object3D class

Having a background in AS3/Away3D, I am new to THREE.js and I am trying to create a custom object class that extends THREE.Object3D for my scene. CustomObject will contain behavioral properties and methods, with each instance having its own data object det ...

Showing Firestore Data as a map type: Issue encountered - React child cannot be an Object

Retrieving data from firestore: const [product, setProduct] = useState([]); const fetchProducts = async () => { const querySnapshot = await getDocs(collection(db, "products")); const productsArray = []; querySnapshot.forEach((doc) => { ...