Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert anything to a String safely in JavaScript

If I have:

var test = {toString: function(){alert("evil code"); return "test";}};

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.

like image 289
erikvold Avatar asked Nov 30 '10 04:11

erikvold


People also ask

How do you turn something into a string in JavaScript?

Values can be explicitly converted to strings by calling either String() or n. toString() . With the String() function, let's convert a Boolean value to a string by passing the value true into the parameters for String() .

How do you turn an object into a string?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.

How do you convert JavaScript object to string explain with example?

Example 1: Convert Object to String Using JSON.stringify() method is used to convert an object to a string. The typeof operator gives the data type of the result variable.


2 Answers

JavaScript allows you to modify the properties of pretty much any object that is accessible to your script, including Object.prototype itself, meaning any object is vulnerable to "evil code" in the manner that you explained.

Only primitives are guaranteed to be safe, so the only way to ensure that "evil code" is never executed is to do something like this:

function safeToString(x) {
  switch (typeof x) {
    case 'object':
      return 'object';
    case 'function':
      return 'function';
    default:
      return x + '';
  }
}
like image 104
casablanca Avatar answered Nov 08 '22 11:11

casablanca


One option is:

Object.prototype.toString.call(test)

This gives:

"[object Object]"

in the case of test. Basically, it just gives type information. However, I wonder what the exact scenario is here. How is the evil object getting loaded into the page? If they can execute arbitrary code on the page, you're basically out of luck. Among other things, it is then possible to redefine Object.prototype.toString.

like image 39
Matthew Flaschen Avatar answered Nov 08 '22 13:11

Matthew Flaschen