Now, I’m working with userscript for a browser game. And I have some problems with sandbox and initialization.
As a solution, I found a way with creating a new element (script) and inserting the object in element.
var script = document.createElement("script");
script.type = "text/javascript";
script.innerHTML = "var Class = { ... }";
document.body.appendChild(script);
But I have a very large object and convert it to a string rather problematic and time consuming.
I have an object that looks like this:
{
addToStorage : Function,
getFromStorage : Function,
getID : Function
settings : Object,
langs : Object,
init : Function,
version : Number,
author: String
}
Any ideas, how to convert it to string or insert into global window?
Sorry for my bad English.
In Firefox, you can use the
.toSource()function on objects. So the answer is ditch Chrome and switch to Firefox. (^_^)But assuming you don’t want to do that, the answer gets messy, as even
JSON.stringify()won’t work if the object as function properties, like yours does.So, you can inject your object source using a multiline string (see the link for a variety of techniques).
Or you can make or use a an object stringifier like
objToString, below. Warning,objToStringis just a quick and dirty first attempt, you might be smarter to grab something like JavaScript var_export, instead.