Подтвердить что ты не робот

Получить все пользовательские свойства окна?

Есть ли способ узнать все пользовательские свойства и переменные окна (глобальные переменные) в javascript?

Я попробовал console.log(window), но список бесконечен.

4b9b3361

Ответ 1

Вам нужно будет сделать работу для себя. Читайте во всех свойствах, в первый раз, когда сможете. С этого момента вы можете сравнить список свойств со своим статическим.

var globalProps = [ ];

function readGlobalProps() {
    globalProps = Object.getOwnPropertyNames( window );
}

function findNewEntries() {
    var currentPropList = Object.getOwnPropertyNames( window );

    return currentPropList.filter( findDuplicate );

    function findDuplicate( propName ) {
        return globalProps.indexOf( propName ) === -1;
    }
}

Итак, теперь мы можем пойти как

// on init
readGlobalProps();  // store current properties on global object

и позже

window.foobar = 42;

findNewEntries(); // returns an array of new properties, in this case ['foobar']

Конечно, здесь предостережение заключается в том, что вы можете только "заморозить" глобальный список свойств в то время, когда ваш script может называть его самым ранним временем.

Ответ 2

Вы также можете сравнить окно с чистой версией окна, а не пытаться сделать снимок во время выполнения для сравнения. Я запускал это в консоли, но вы можете превратить его в функцию.

// make sure it doesn't count my own properties
(function () {
    var results, currentWindow,
    // create an iframe and append to body to load a clean window object
    iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    // get the current list of properties on window
    currentWindow = Object.getOwnPropertyNames(window);
    // filter the list against the properties that exist in the clean window
    results = currentWindow.filter(function(prop) {
        return !iframe.contentWindow.hasOwnProperty(prop);
    });
    // log an array of properties that are different
    console.log(results);
    document.body.removeChild(iframe);
}());

Ответ 3

Это в том же духе, что и ответ @jungy, но мы можем сделать это в 3 строки:

document.body.appendChild(document.createElement('div')).innerHTML='<iframe id="temoin" style="display:none"></iframe>';

for (a in window) if (!(a in window.frames[window.frames.length-1])) console.log(a, window[a])

document.body.removeChild($$('#temoin')[0].parentNode);

Сначала мы добавляем скрытый iframe; затем мы проверяем существующие переменные на соответствие стандартному JavaScript API в iframe; затем мы удаляем iframe.

Для более удобной работы может быть полезно отсортировать результаты в алфавитном порядке, и это все еще возможно в трехстрочной версии:

document.body.appendChild(document.createElement('div')).innerHTML='<iframe id="temoin" style="display:none"></iframe>';

Object.keys(window).filter(a => !(a in window.frames[window.frames.length-1])).sort().forEach((a,i) => console.log(i, a, window[a]));

document.body.removeChild($$('#temoin')[0].parentNode);

И это может быть упаковано в закладку:

javascript:document.body.appendChild(document.createElement('div')).innerHTML='<iframe%20id="temoin"%20style="display:none"></iframe>';Object.keys(window).filter(a=>!(a%20in%20window.frames[window.frames.length-1])).sort().forEach((a,i)=>console.log(i,a,window[a]));document.body.removeChild(document.querySelectorAll('#temoin')[0].parentNode);throw 'done';

Ответ 4

Может быть это?:

for (var property in window)
{
    if (window.hasOwnProperty(property))
        console.log(property)
}