Deciding whether an item qualifies as a Map in JavaScript

I have been working on developing a function that will return true if the argument provided to it is an instance of a JavaScript Map.

When we use typeof new Map(), the returned value is object and there isn't a built-in Map.isMap method available.

Here is the code snippet I have come up with:

function isMap(v) {
  return typeof Map !== 'undefined' &&
    Map.prototype.toString.call(v) === '[object Map]' ||
    v instanceof Map;
}

(function test() {
  const map = new Map();

  write(isMap(map));

  Map.prototype.toString = function myToString() {
    return 'something else';
  };

  write(isMap(map));
}());

function write(value) {
  document.write(`${value}<br />`);
}

However, testing maps across frames and in cases where toString() has been changed, the isMap function fails (reasons explained here).

For example:

<iframe id="testFrame"></iframe>
<script>
  const testWindow = document.querySelector('#testFrame').contentWindow;
  // returns false when toString is overridden 
  write(isMap(new testWindow.Map())); 
</script>

If you want to see a detailed demonstration of this issue, check out this Code Pen link.

I am looking for a way to modify the isMap function so that it can accurately identify instances of Maps even when toString is overridden or the map object is from another frame. Can this be achieved?

Answer №1

To verify, use

Object.prototype.toString.call(new testWindow.Map)
.

If it's been modified, you may be facing a difficult situation.

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

How to disable typescript eslint notifications in the terminal for .js and .jsx files within a create-react-app project using VS Code

I'm currently in the process of transitioning from JavaScript to TypeScript within my create-react-app project. I am facing an issue where new ESLint TypeScript warnings are being flagged for my old .js and .jsx files, which is something I want to avo ...

Using Javascript regex to capture the image name from a CSS file

As I work with JavaScript regex, my goal is to extract the image name and extension as a capture group of CSS properties. Criteria Must start with "url" Followed by brackets Optional quotes inside brackets The location can include path information Must ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

Using $.getJSON is not functioning properly, but including the JSON object directly within the script is effective

I'm currently working on dynamically creating a simple select element where an object's property serves as the option, based on specific constraints. Everything is functioning properly when my JSON data is part of the script. FIDDLE The follow ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...

Variables in the $scope object in AngularJS

Within my $scope in angularJS, I am working with two types of variables. 1). $scope.name and $scope.title are linked to input boxes in the UI html code. 2). On the other hand, $scope.sum and $scope.difference are internally used within my JS code. I need ...

Tips for integrating Material UI with useRef

There seems to be an issue with the code, but I haven't been able to pinpoint exactly what it is. My question is: How do you properly use useRef with Material UI? I am attempting to create a login page. The code was functioning fine with the original ...

Add a fading transition feature to images that are loaded at a later time

I used a clever technique to create a blur effect by loading a small, lightweight image first. Once the main background image is loaded, it swaps out the 'data-src' with the actual image. However, I am facing an issue with the abrupt transition, ...

How can I display only the y-axis values and hide the default y-axis line in react-chartjs-2?

Although I have some experience with chartjs, I am struggling to figure out how to hide the default line. To clarify, I have attached an image that illustrates the issue. I would like to achieve a result similar to this example: https://i.sstatic.net/UXMpi ...

Asynchronous Return in NodeJS Class Methods

Currently, I am in the process of developing a JavaScript class that includes a login method. Here is an overview of my code: const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config ...

Express.js fails to redirect to the sign-in page after successfully retrieving the username from the MySQL database

I have encountered an issue while trying to retrieve the username from a MySQL database. The code I am using successfully retrieves the username, but when an error occurs, instead of redirecting to /signin, it redirects to /admin. Adding res.redirect(&ap ...

Toggle visibility between 2 distinct Angular components

In my application, I have a Parent component that contains two different child components: inquiryForm and inquiryResponse. In certain situations, I need to toggle the visibility of these components based on specific conditions: If a user clicks the subm ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Implementing personalized callback methods for AJAX requests in Prototype

After refactoring my code to use proper objects, I am facing an issue with getting Prototype's AJAX.Request to work correctly. The code snippet below is functioning within the context of YUI's DataTable: SearchTable.prototype.setTableColumns = f ...

Updating the minimum date based on the user's previous selection using React JS and Material UI

In my material UI, I have two date pickers set up: From Date - <KeyboardDatePicker value={initialDateFrom} disableFuture={true} onChange={handleFromDateChange} > </KeyboardDatePicker> To Date - <KeyboardDatePicker value={initialDateTo} ...

Issue with React Router functionality not functioning

I am currently facing an issue with my react-router setup. You can find the code I am using by visiting this link - https://github.com/rocky-jaiswal/lehrer-node/tree/master/frontend Although it is a basic setup for react-router, I am experiencing difficu ...

JavaScript menu that pops up

Hello everyone, I've recently created an HTML5 file that, when clicked on a specific href link, is supposed to display an image in a smooth and elegant manner. However, so far it hasn't been working for me as expected. Instead of smoothly popping ...

Display a span element using jQuery datatable to indicate that the update operation was

I have implemented inline editing using jQuery Datatables. Currently, I am trying to display a green checkmark when a record gets updated. Below is the ajax call that populates the table: $.ajax({ url: 'api/massEditorSummary.php', type: &ap ...

Error Message: Unable to access properties of an undefined object while interacting with an API in a React application

Creating a Weather application in React JS that utilizes the OpenWeatherMapAPI to display dynamic backgrounds based on the API response. I need to access the data at 'data.weather[0].main' which will contain values like 'Clear', ' ...

Utilize jQueryUI sortable to serialize a list item within an unordered list

I'm looking to learn how to generate a JSON or serialize from a ul element with nested list items. Here's an example: <ul class="menu send ui-sortable"> <li id="pageid_1" class="ui-sortable-handle">Inscription <ul class="menu ...