How to detect creation of new global variables? - javascript

I want watch for the creation of new global variables in Javascript so that, anytime a global variable is created, an event is fired.
I've heard of the watch() function but that is only for watching for specific variable names. I want a catchall.

If you already know which names pollute your global namespace (see Intercepting global variable definition in javascript), you can use this trick to figure out when does it actually happen:
window.__defineSetter__('someGlobalVar', function() {
debugger;
});
Be sure to have your developer tools open when you run this.
Obviously works only if your browser supports __defineSetter__ but that's true for modern browsers. Also, don't forget to remove your debug code after you've finished.
Found here.

I don't know how to make this work "on demand" as soon as a var is created, but I can suggest a polling approach. In a browser window, all global become a member of the global "window" object. (Because technically, "window" is the "global object"). So you could do something like the following:
1) enumerate all the properties on a window
window.proplist = window.proplist || {};
for (propname in window) {
if (propname !== "proplist") {
window.proplist[propname] = true;
}
}
2) Set a timer to periodically "poll" window for new properties
setInterval(onTimer, 1000);
3) Wake up on the timer callback and look for new props
function onTimer() {
if (!window.proplist) {
return;
}
for (propname in window) {
if (!(window.proplist[propname])) {
window.proplist[propname] = true;
onGlobalVarCreated(propname);
}
}
}

Afaik, .watch() is only SpiderMonkey (Firefox).
I played around with a polling function, I finally came up with this:
var mywatch = (function() {
var last = {
count: 0,
elems: {}
};
return function _REP(cb) {
var curr = {
count: 0,
elems: {}
},
diff = {};
for(var prop in window) {
if( window.hasOwnProperty(prop) ) {
curr.elems[prop] = window[prop]; curr.count++;
}
}
if( curr.count > last.count ) {
for(var comp in curr.elems) {
if( !(comp in last.elems) ) {
diff[comp] = curr.elems[comp];
}
}
last.count = curr.count;
last.elems = curr.elems;
if(typeof cb === 'function')
cb.apply(null, [diff]);
}
setTimeout(function() {
_REP(cb);
}, 400);
};
}());
And then use it like:
mywatch(function(diff) {
console.log('NEW GLOBAL(s): ', diff);
});
Be aware that this only handles new globals. But you can easily extend this for the case last.count > curr.count. That would indicate that global variables were deleted.

You cant have an event fired when some script does var v = 10, but as selbie said, you can poll the window object... I meant to suggest the same, but he beat me to it. Here's my other example... you count how many window objects are there, and execute GlobalVarCreated() function:
var number_of_globals = 0; //last known globals count
var interval = window.setInterval(function(){
var new_globals_count = 0; //we count again
for(var i in window) new_globals_count++; //actual counting
if(number_of_globals == 0) number_of_globals = new_globals_count; //first time we initialize old value
else{
var number_of_new_globals = new_globals_count - number_of_globals; //new - old
if(number_of_new_globals > 0){ //if the number is higher then 0 then we have some vars
number_of_globals = new_globals_count;
for(var i = 0; i<number_of_new_globals; i++) GlobalVarCreated(); //if we have 2 new vars we call handler 2 times...
}
}
},300); //each 300ms check is run
//Other functions
function GlobalVarCreated(){}
function StopInterval(){window.clearInterval(interval);}
You can load up that code in Chrome or FF console only change: function GlobalVarCreated(){console.log("NEW VAR CREATED");} and test it:
var a = 10
b = 10
String NEW VAR CREATED is displayed 2 times.

Related

How do I use an array instead of the variables in this repetitive function?

So, I have this little code in my js file:
window.onload = function Equal() {
var a = 'b1'
var b = 'box1'
var bookstorname = localStorage.getItem(a)
if (bookstorname == 1) {
document.getElementById(b).setAttribute('checked','checked');
}
if (bookstorname == 0) {
document.getElementById(b).removeAttribute('checked','checked');
}
var a = 'b2'
var b = 'box2'
var bookstorname = localStorage.getItem(a)
if (bookstorname == 1) {
document.getElementById(b).setAttribute('checked','checked');
}
if (bookstorname == 0) {
document.getElementById(b).removeAttribute('checked','checked');
}
}
The function itself is not important (it equals checkboxvalues set in the localstorage), but I execute it 2 times. First time with var a & b set to 'b1' & 'box1'. Then I run the script again (same script), but with var a & b set to 'b2' & 'box2'. Now, this code works, but my question is if there is a shorter way to write this? I can imagine some sort of array with a loop, but I could not get it to work for some reason. The 2 variables are pairs, and I know this might be a dumb question, but I can't find the answer anywhere.
You can use a second function which will accept the local storage key and the checkbox id like
window.onload = function Equal() {
setCheckboxState('box1', 'b1');
setCheckboxState('box2', 'b2');
}
function setCheckboxState(id, key) {
document.getElementById(id).checked = 1 == localStorage.getItem(key);
}
You might separate common logic into another function
window.onload = function Equal() {
function extractFromStorage(a, b) {
var bookstorname = localStorage.getItem(a)
if (bookstorname == 1) {
document.getElementById(b).setAttribute('checked','checked');
}
if (bookstorname == 0) {
document.getElementById(b).removeAttribute('checked','checked');
}
}
extractFromStorage('b1', 'box1');
extractFromStorage('b2', 'box2');
}
function doTheStuff(a, b) {
var bookstorname = localStorage.getItem(a)
if (bookstorname == 1) {
document.getElementById(b).setAttribute('checked','checked');
}
if (bookstorname == 0) {
document.getElementById(b).removeAttribute('checked','checked');
}
}
window.onload = function Equal() {
doTheStuff('b1', 'box1');
doTheStuff('b2', 'box2');
}
?
This is how I would do it.
There are several problems with your code.
You do not check that the element you are stetting an attribute to
exists. You do not check if the localStorage item you get is
defined.
You pollute the global name space with the function name Equal.
That function should not be named with a capital as it is not a Object generator.
There is no need to use setAttribute and removeAttribute, in
fact removeAttribute makes no sense in this case as you can not
remove the checked attribute from the element. BTW why use setAttribute here and not for window.onload?
The checked attribute is either true or false, it does not use the
string "checked"
Binding the load event via the onload attribute is not safe as you may
block 3rd party code, or worse 3rd party code may block you.
There is no error checking. DOM pages are dynamic environments, pages
have adverts and content from many places that can interfer with your
code. Always code with this in mind. Check for possible errors and deal with them in a friendly way for the end user. In this case I used an alert, not friendly for a normal user but for you the coder.
My solution.
// add an event listener rather than replace the event listener
window.addEventListener(
"load", // for the load event
function(){
// the update function that is called for each item;
var update = function(item){
// the right hand side equates to true if the localstorage
// is equal to "1". LocalStorage allways returns a string or
// undefined if the key is not defined.
item.element.checked = localStorage[item.storageName] === "1";
}
// safe element getter
var getElement = function(eId){
var e = document.getElementById(eId); // try and get the element
if(e === null){ // does it exist?
throw "Missing element:"+eId; // no then we can not continue
// the program stops here unless
// you catch the error and deal with
// it gracefully.
}
return e; //ok return the element.
}
// Item creator. This creates a new item.
// sName is the local storage name
// eId id the element ID
var item = function(sName, eId){
return {
storageName: sName, // set the loaclStorage name
element:getElement(eId); // get the element and check its safe
};
}
// make it all safe
try{
// create an array of items.
var items = [
item("b1","box1"),
item("b2","box2")
];
// for each item update the element status
items.forEach(update);
}catch(e){
alert("Could not update page?");
}
}
);

Javascript reference in loop: "Uncaught TypeError: Cannot read property 'value' of undefined"

I tried debugging my code for like a few hour but I got nothing out of it. The issue is that it makes absolutely no sense on why it reports an error every time I tried to use document.forms[0][i] (i as the iterator) in the event listener but "this" satisfies the code.
//broken
var addListeners = function() {
var i;
var formFields = document.forms[0];
var formSubmit = formFields["submit"];
for (i = 0; i < formFields.length; i++) {
if (formFields[i] != formSubmit) {
formFields[i].onblur = (function () {
checkNonEmpty(formFields[i]);
});
}
}
};
//works
var addListeners = function() {
var i;
var formFields = document.forms[0];
var formSubmit = formFields["submit"];
for (i = 0; i < formFields.length; i++) {
if (formFields[i] != formSubmit) {
formFields[i].onblur = (function () {
checkNonEmpty(this);
});
}
}
};
Wouldn't "this" refer to document.forms[0][i]?... formFields references to document.forms[0]. However the exact same code (with "this" where formFields[i] is at) works just fine.
Here is the demo: http://jsfiddle.net/PbHwy/
Cranio's answer already contains the root of the matter. To get rid of this you can either include formFields[i] by using closures
var blurCallbackGenerator = function(element){
return function () {
checkNonEmpty(element);
};
};
formFields[i].onblur = blurCallbackGenerator(formFields[i]);
/* // dense version:
formFields[i].onblur = (function(element){
return function () {
checkNonEmpty(element);
};
})(formFields[i]);
*/
or simply using this.
See also:
MDN: Creating closures in loops: A common mistake
Because you define formFields in a scope outside (or better, different than) the event listener. When the event listener is called, it is called not in the addListeners function where you define formFields, but "independently", so the reference is lost and its value is undefined (but this works because it is not dependent on that scope).
The problem is that the variable i (referred to in each of your handlers) is the exact same variable in each of them, which by the time the loop has finished has value formFields.length+1 and is therefore wrong for all of them. Try this instead [note: the below used to say something VERY WRONG before I edited it -- thanks to Zeta for pointing out my mistake]:
var addListeners = function() {
var i;
var formFields = document.forms[0];
var formSubmit = formFields["submit"];
for (i = 0; i < formFields.length; i++) {
if (formFields[i] != formSubmit) {
formFields[i].onblur = (function(j) {
return (function () {
checkNonEmpty(formFields[j]);
})(i);
});
}
}
};
and you'll find it works (unless there's another bug that I haven't noticed).
If you can afford to support only Javascript 1.7 and above, you can instead write your old code but make your for look like this: for (let i=0; i<formFields.length; i++). But you quite possibly can't.

Javascript - dumping all global variables

Is there a way in Javascript to get a list or dump the contents of all global variables declared by Javascript/jQuery script on a page? I am particularly interested in arrays. If I can get the array names, it will be enough to me. Seeing its values is a bonus.
Object.keys( window );
This will give you an Array of all enumerable properties of the window object, (which are global variables).
For older browsers, include the compatibility patch from MDN.
To see its values, then clearly you'll just want a typical enumerator, like for-in.
You should note that I mentioned that these methods will only give you enumerable properties. Typically those will be ones that are not built-in by the environment.
It is possible to add non-enumerable properties in ES5 supported browsers. These will not be included in Object.keys, or when using a for-in statement.
As noted by #Raynos, you can Object.getOwnPropertyNames( window ) for non-enumerables. I didn't know that. Thanks #Raynos!
So to see the values that include enumerables, you'd want to do this:
var keys = Object.getOwnPropertyNames( window ),
value;
for( var i = 0; i < keys.length; ++i ) {
value = window[ keys[ i ] ];
console.log( value );
}
The following function only dumps global variables that have been added to the window object:
(function(){
//noprotect <- this comment prevents jsbin interference
var windowProps = function() {
// debugger;
var result = {};
for (var key in window) {
if (Object.prototype.hasOwnProperty.call(window, key)) {
if ((key|0) !== parseInt(key,10)) {
result[key] = 1;
}
}
}
window.usedVars = result;
};
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'about:blank';
document.body.appendChild(iframe);
var fwin = iframe.contentWindow;
var fdoc = fwin.document;
fdoc.open('text/html','replace');
fdoc.write('<!DOCTYPE html><body><script>window.onload = ' + windowProps.toString() + '<\u002Fscript>');
fdoc.close();
var button = document.createElement('input');
button.type = 'button';
button.value = 'go';
document.body.appendChild(button);
button.onclick = function() {
var clean = fwin.usedVars;
windowProps();
var dirty = window.usedVars;
for (var key in clean) {
delete dirty[key];
}
for (var variable in dirty) {
var div = document.createElement('div');
div.textContent = variable;
document.body.appendChild(div);
}
document.body.removeChild(button);
document.body.removeChild(iframe);
};
})();
It works by using an iframe to get a clean list of global window variables, then comparing that with the list of global variables in the current window. It uses a button because the iframe runs asynchronously. The code uses a global variable because that makes the code easier to understand.
You can see it working here or here, although note that these examples show many global variables "leaked" by jsbin itself (different depending on which link you use).
Since all global variables are properties of the window object, you can get them using:
for(var key in window) { // all properties
if(Array.isArray(window[key])) { // only arrays
console.log(key, window[key]); // log key + value
}
}
Since all default/inherited properties are not plain arrays (mostly host objects or functions), the Array.isArray check is sufficient.
To get "globals" object you can use this function:
function globals() { return this; }
Here is the test:
http://jsfiddle.net/EERuf/
window is the global object in a browser, and you can use a for..in loop to loop through its properties:
if(!Array.isArray) {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
}
for(var x in window) {
if(Array.isArray(window[x])) {
console.log('Found array ' + x + ' in ' + window + ', it has the value ' + window[x] + '!');
}
}
You can use npm package called get-globals. It compares properties of window with fresh-created iframe to print only variables declared by dev(s), not browser vendor.
Greasymonkey script to get leaked globals
// ==UserScript==
// #name SCI
// #namespace ns
// #version 1
// #grant none
// #run-at document-start
// ==/UserScript==
console.log('SCI loaded');
var SCI = window.SCI = {
defprops: [],
collect: function(){
var wprops = [];
for(var prop in window){
wprops.push(prop);
}
return wprops;
},
collectDef: function(){
this.defprops = this.collect();
},
diff: function(){
var def = this.defprops,
cur = this.collect();
var dif = [];
for(var i = 0; i < cur.length; i++){
var p = cur[i];
if(def.indexOf(p) === -1){
dif.push(p);
}
}
return dif;
},
diffObj: function(){
var diff = this.diff();
var dobj = {};
for (var i = 0; i < diff.length; i++){
var p = diff[i];
dobj[p]=window[p];
}
return dobj;
}
};
SCI.collectDef();
To use run in console SCI.diff() to get list of names or SCI.diffObj() to get object with variables
Here’s a simple, more modern snippet that logs an object with the globals and their values (rather than just the global variable names), which is usually what I’m looking for when debugging:
(function () {
const iframe = document.createElement('iframe')
iframe.setAttribute('hidden', '')
iframe.src = 'about:blank'
iframe.onload = function () {
// Iterate through the properties of the current `window` and reduce the output
// to only properties that are not in the iframe’s `window`.
console.debug(Object.entries(window).reduce((reducedObj, [property, value]) => {
// Check if the property does not exist in the iframe and if so, add it to
// the output object.
if (! (property in iframe.contentWindow))
reducedObj[property] = value
return reducedObj
}, {})))
// Clean up the iframe by removing it from the DOM.
iframe.remove()
}
// Append the iframe to the DOM to kick off loading.
document.body.append(iframe)
})()
Tip: You can also swap 'about:blank' with window.location to get only the globals set since the page was first loaded.
This uses an iframe to determine which properties to ignore like robocat’s answer, but it’s based on David Walsh’s solution.

Why don't instance methods work as expected?

(function() {
window.gArr = new ExtArray();
})();
function ExtArray() {
this.bounce = function() {
document.write("Bounced successfully!");
};
}
ExtArray.prototype = new Array;
ExtArray.prototype.first = function() {
document.write(this[0]);
}
var eArr = new ExtArray();
//all three work
eArr.bounce();
eArr.push("I am first! ");
eArr.first();
// invoking global
gArr.bounce(); // it works
gArr.push("No, it is me who is really first! "); // doesn't work
gArr.first(); // doesn't work
Why doesn't it work?
> (function() {
> window.gArr = new ExtArray(); })();
Why is that preferred to just:
var gArr = new ExtArray();
they are functionally identical (unless there is no window object in which case the first will fail);
> function ExtArray() {
> this.bounce = function() {
> document.write("Bounced successfully!");
> }; }
Using document.write after the page has finished loading will first clear the entire document (i.e. everything between the HTML tags) and write whatever is passed to the function (in this case, a two word string).
> ExtArray.prototype = new Array;
> ExtArray.prototype.first = function() {
> document.write(this[0]);
> }
As above, document.write is destructive.
> var eArr = new ExtArray();
> //all three work
> eArr.bounce();
> eArr.push("I am first! ");
> eArr.first();
Presumably this is running before the load event then.
> // invoking global
> gArr.bounce(); // it works
> gArr.push("No, it is me who is really first! "); // doesn't work
> gArr.first(); // doesn't work
The bits that "don't work" are because you initialised gArr before you modified ExtArray.prototype, so it has the instance method bounce but still has the default prototype when the constructor was declared.
Remember that once declarations are done, the code runs in sequence so gArr = new ExtArray() runs before ExtArray.prototype = new Array; and so on.
Also, an instance has an internal prototype property that references the constructor's prototype at the instant it was created and can't be changed afterward (except for Mozilla's deprecated proto property). So changing the contsructor's prototype doesn't change the internal prototype of any instances that have already been constructed.
You should define window.gArr after you define ExtArray.prototype:
function ExtArray() {
this.bounce = function() {
document.write("Bounced successfully!");
};
}
ExtArray.prototype = new Array;
ExtArray.prototype.first = function() {
document.write(this[0]);
}; // <-- semicolon will be REQUIRED here.
(function() {
window.gArr = new ExtArray();
})();
DEMO: http://jsfiddle.net/Vg3Ze/

How to write this JavaScript code without eval?

How to write this JavaScript code without eval?
var typeOfString = eval("typeof " + that.modules[modName].varName);
if (typeOfString !== "undefined") {
doSomething();
}
The point is that the name of the var that I want to check for is in a string.
Maybe it is simple but I don't know how.
Edit: Thank you for the very interesting answers so far. I will follow your suggestions and integrate this into my code and do some testing and report. Could take a while.
Edit2: I had another look at the could and maybe itis better I show you a bigger picture. I am greatful for the experts to explain so beautiful, it is better with more code:
MYNAMESPACE.Loader = ( function() {
function C() {
this.modules = {};
this.required = {};
this.waitCount = 0;
this.appendUrl = '';
this.docHead = document.getElementsByTagName('head')[0];
}
function insert() {
var that = this;
//insert all script tags to the head now!
//loop over all modules:
for (var modName in this.required) {
if(this.required.hasOwnProperty(modName)){
if (this.required[modName] === 'required') {
this.required[modName] = 'loading';
this.waitCount = this.waitCount + 1;
this.insertModule(modName);
}
}
}
//now poll until everything is loaded or
//until timout
this.intervalId = 0;
var checkFunction = function() {
if (that.waitCount === 0) {
clearInterval(that.intervalId);
that.onSuccess();
return;
}
for (var modName in that.required) {
if(that.required.hasOwnProperty(modName)){
if (that.required[modName] === 'loading') {
var typeOfString = eval("typeof " + that.modules[modName].varName);
if (typeOfString !== "undefined") {
//module is loaded!
that.required[modName] = 'ok';
that.waitCount = that.waitCount - 1;
if (that.waitCount === 0) {
clearInterval(that.intervalId);
that.onSuccess();
return;
}
}
}
}
}
};
//execute the function twice a second to check if all is loaded:
this.intervalId = setInterval(checkFunction, 500);
//further execution will be in checkFunction,
//so nothing left to do here
}
C.prototype.insert = insert;
//there are more functions here...
return C;
}());
var myLoader = new MYNAMESPACE.Loader();
//some more lines here...
myLoader.insert();
Edit3:
I am planning to put this in the global namespace in variable MYNAMESPACE.loadCheck, for simplicity, so the result would be, combining from the different answers and comments:
if (MYNAMESPACE.loadCheck.modules[modName].varName in window) {
doSomething();
}
Of course I will have to update the Loader class where ever "varName" is mentioned.
in JS every variable is a property, if you have no idea whose property it is, it's a window property, so I suppose, in your case, this could work:
var typeOFString = typeof window[that.modules[modName].varName]
if (typeOFString !== "undefined") {
doSomething();
}
Since you are only testing for the existence of the item, you can use in rather than typeof.
So for global variables as per ZJR's answer, you can look for them on the window object:
if (that.modules[modName].varName in window) {
...
}
If you need to look for local variables there's no way to do that without eval. But this would be a sign of a serious misdesign further up the line.

Categories