简体   繁体   中英

Converting the JavaScript Window Object to JSON

Obviously, this will seem at first that it cannot be done, but I will state clearly that I have successfully converted the JavaScript window object to JSON. What I need help with is how to do so in a more intelligent way than I am doing now.

The process works now like this:

1) A new object is created and each key from the window key is copied to the new object. A list of commonly known keys is not added to the new object (ex. WebSocket). 2) A function called getArray recursively cleans each sub-object and saves it as JSON. The result looks like this {'key':'JSON_{....}'} or {'key':'JSON_{{'key':'JSON_{....}'}}'}. The idea is to catch the error at the smallest level so that the final JSON object is composed of key:JSON_string values. The other critical point is to catch circular objects. If the object has any of a long list of keys, then it is excluded (ex. tagName).

The problem is that this code is a bit unstable. It just recently ceased working on our site and I don't have the mind to improve it.

I will accept any solution that converts the window object to JSON (or any text format that can be decoded properly). I suggest that a partial solution, a function that will detect circular and non-JSON-encodable objects with 100%, will be the best, if it is possible. It would take a genius to produce, but I believe that it is possible.

The purpose of this is for user-sent bug reports to show the state of our JavaScript. There are too many objects to enumerate 1, by 1, and even our user-created objects contain a un-encodable objects. It is very useful and relevant for the web.

Here is current code, design pattern as described. getWindow()

getWindow: function()
    {
        var obj2 = {};
        for (var i in window)
        {
            obj2[i] = 1;
        }
        var keys = ["RequestLogs", "WebSocket", "ClickLogs", "$", "jQuery", "window", "top", "location", "external", "chrome", "document", "i", "arr", "webkitNotifications", "localStorage", "sessionStorage", "applicationCache", "webkitStorageInfo", "indexedDB", "webkitIndexedDB", "crypto", "CSS", "performance", "console", "devicePixelRatio", "styleMedia", "parent", "opener", "frames", "self", "defaultstatus", "defaultStatus", "status", "name", "length", "closed", "pageYOffset", "pageXOffset", "scrollY", "scrollX", "screenTop", "screenLeft", "screenY", "screenX", "innerWidth", "innerHeight", "outerWidth", "outerHeight", "offscreenBuffering", "frameElement", "clientInformation", "navigator", "toolbar", "statusbar", "scrollbars", "personalbar", "menubar", "locationbar", "history", "screen", "postMessage", "close", "blur", "focus", "ondeviceorientation", "ondevicemotion", "onunload", "onstorage", "onresize", "onpopstate", "onpageshow", "onpagehide", "ononline", "onoffline", "onmessage", "onhashchange", "onbeforeunload", "onwaiting", "onvolumechange", "ontimeupdate", "onsuspend", "onsubmit", "onstalled", "onshow", "onselect", "onseeking", "onseeked", "onscroll", "onreset", "onratechange", "onprogress", "onplaying", "onplay", "onpause", "onmousewheel", "onmouseup", "onmouseover", "onmouseout", "onmousemove", "onmouseleave", "onmouseenter", "onmousedown", "onloadstart", "onloadedmetadata", "onloadeddata", "onload", "onkeyup", "onkeypress", "onkeydown", "oninvalid", "oninput", "onfocus", "onerror", "onended", "onemptied", "ondurationchange", "ondrop", "ondragstart", "ondragover", "ondragleave", "ondragenter", "ondragend", "ondrag", "ondblclick", "oncuechange", "oncontextmenu", "onclose", "onclick", "onchange", "oncanplaythrough", "oncanplay", "oncancel", "onblur", "onabort", "onwheel", "onwebkittransitionend", "onwebkitanimationstart", "onwebkitanimationiteration", "onwebkitanimationend", "ontransitionend", "onsearch", "getSelection", "print", "stop", "open", "showModalDialog", "alert", "confirm", "prompt", "find", "scrollBy", "scrollTo", "scroll", "moveBy", "moveTo", "resizeBy", "resizeTo", "matchMedia", "requestAnimationFrame", "cancelAnimationFrame", "webkitRequestAnimationFrame", "webkitCancelAnimationFrame", "webkitCancelRequestAnimationFrame", "captureEvents", "releaseEvents", "atob", "btoa", "setTimeout", "clearTimeout", "setInterval", "clearInterval", "TEMPORARY", "PERSISTENT", "getComputedStyle", "getMatchedCSSRules", "webkitConvertPointFromPageToNode", "webkitConvertPointFromNodeToPage", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL", "openDatabase", "addEventListener", "removeEventListener", "dispatchEvent"];
        for (var iii in keys)
        {
            var key = keys[iii];
            if (obj2[key])
                delete(obj2[key]);
        }

        for (var i in obj2)
        {
            obj2[i] = window[i];
        }

        return this.getArray(obj2, 0);
    },

getArray()

getArray: function(obj, count)
    {
        try {
            var data = this._getArray(obj, count);
            var cache = [];
            if (typeof data === 'object' && data !== null) {
                if (cache.indexOf(data) !== -1) {
                    // Circular reference found, discard key
                    return 'circular';
                }
                // Store value in our collection
                cache.push(data);
            }
            if (typeof data == 'object')
                return 'JSON_' + JSON.stringify(data);
            else
                return data;
            //return data;
        } catch (e)
        {
            console.log(e);
            return '';
        }
    }

,

_getArray

_getArray: function(obj, count)
    {
        count = isset(count) ? count : 0;
        if (obj == window && count > 0)
            return 'window';
        if (obj && typeof obj == 'object')
        {
            if (Object.keys(obj).length >= 100 && count > 0)
            {
                return 'object,>100keys';
            }
            if (obj['tagName'])
            {
                return obj['tagName'];
            }

            if (count > 0)
            {
                var keys = ['$', 'tagName', 'scrollTop', 'contentEditable', 'documentURI', 'documentElement', 'context', 'selector', 'jquery', 'ATTRIBUTE_NODE', 'nodeName'];
                for (var ii in keys)
                {
                    if (obj[0] && obj[0].length == 3)
                    {
                        ///log2(obj);
                    }
                    var key = keys[ii];
                    if (obj[key])
                    {
                        return ii;
                    }
                }
            }
            if (!$.isPlainObject(obj))
            {
                var obj2 = {};
                for (var ii in obj)
                {
                    obj2[ii] = obj[ii];
                }
                obj = obj2;
            }
        }
        var arr = {};
        for (var i in obj)
        {
            var type = typeof obj[i];
            if (type == 'string' || type == 'number' || type == 'boolean')
            {
                arr[i] = obj[i];
            }

            if (type == 'function')
            {
                var obj2 = {};
                var funcHasData = false;
                for (var ii in obj[i])
                {
                    funcHasData = true;
                    obj2[ii] = obj[i][ii];
                }
                if (funcHasData)
                {
                    arr[i] = obj2;
                }
            }


            if (type == 'object')
            {
                if (count > 5)
                {
                    return '_';
                }
                arr[i] = this.getArray(obj[i], count + 1);
            }
        }
        return arr;
    }

usage: GetLocalProperties(object); or GetLocalProperties.getWindow();

GetLocalProperties = function(obj,parent_objects){
    var keys = Object.getOwnPropertyNames(obj);
    if (typeof parent_objects == 'object')
    {
        if (parent_objects.indexOf(obj) >= 0)
        {
            return 'recursive obj';
        }
        parent_objects = GetLocalProperties.copyArray(parent_objects);
    } else {
        parent_objects = [window];
    }
    //console.log(parent_objects.length);
    if (parent_objects.length > 10)
    {
        return 'depth greater than 10';
    }
    parent_objects.push(obj);
    var new_object = {};
    for (var key_i_key in keys)
    {
        var key_i = keys[key_i_key];
        var value_i = obj[key_i];
        var value_cloned = GetLocalProperties.getKeyValue(value_i,parent_objects);
        new_object[key_i] = value_cloned;
    }
    return new_object;
};
GetLocalProperties.getKeyValue = function (value_i,parent_objects)
{
    GetLocalProperties.last_value_i = value_i;
    GetLocalProperties.last_parent_objects = parent_objects;
    var type = typeof value_i;
    switch (type)
    {
        case 'object':
            if (!value_i)
            {
                return 'value_is_null';
            }
            if (Array.isArray(value_i))
            {
                //return value_i;
            }
            return GetLocalProperties(value_i,parent_objects);
        case 'boolean':
        case 'number':
        case 'string':
            return value_i;
    }
    return 'not_copied';

};
GetLocalProperties.copyArray = function(arr)
{
    var arr_new = [];
    for (var i in arr)
    {
        arr_new.push(arr[i]);
    }
    return arr_new;
};
GetLocalProperties.getWindow = function()
{
    return GetLocalProperties.getObjectClean(window);
};
GetLocalProperties.getObjectClean = function(obj)
{
    var a = GetLocalProperties(obj);
    for (var i in a)
    {
        var value_i = a[i];
        if (typeof value_i == 'string' && value_i == 'not_copied')
        {
            delete(a[i]);
        }
    }
    return a;
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM