I need to listen to some event (if it exists of course) to know when new property was added to window
object. Is that possible?
For example:
I have a code in application that don't know what global variable some library exposes (eg underscore.js which exposes global _
instead of underscore
). I need to be notified that new property was assigned to window
.
There are two ways you could try to do that but neither is a great option.
You can check for changes to the window
object using setInterval
. This will be slow and there will be a delay between when a new property is added to window
and when your code will notice it. Here is some code that shows one way of doing that: http://jsbin.com/vubew/1/edit?js,console
(function(){ 'use strict'; var keys = Object.keys(window).join(); setInterval(function(){ var newKeys = Object.keys(window).join(); if (newKeys !== keys) { console.log('`window` changed'); keys = newKeys; } }, 100); })();
You could use ES7's Object.observe
method. Unfortunately, only Chrome supports it (behind an experimental flag) right now.
Once you determine there has been a change with one of these methods you'd generate an event that your code would be listening for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.