8

I'm trying to stringify a large object with deep hierarchical structure that I have no knowledge of, in order to get rid of it's circular references. It works for the most part except that often I run into same origin policy exception. I have no interest in any child objects with references to other domains or otherwise restricted elements.

JSON.parse(stringify(window));

throws:

Uncaught DOMException: Blocked a frame with origin "http://www.xxxxxx.com" from accessing a cross-origin frame.

How can I avoid the exception by gracefully skipping what causes it and complete the execution of my code given that I have no control over the native JSON.stringify() code?

JSON.stringify() is just an example here, I guess more generally what I'm asking is how to evade same origin policy exception if you are not trying to violate it but have to deal with it like in this case?

Saba Ahang
  • 578
  • 9
  • 24
  • Possible duplicate of [Ways to circumvent the same-origin policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – buzzsaw Oct 18 '15 at 18:52
  • 2
    @buzzsaw I've read that. It rather discusses ways to circumvent the error using technics that allow you to access across domains resources whereas, I'm trying to avoid the error by not causing it in the first place. I don't need to access across domains and don't even know what references and to what different domains are causing the error. I simply want to skip and ignore – Saba Ahang Oct 18 '15 at 19:39

1 Answers1

1

Try this! First you need to remove all iframes on the page to prevent the cross origin error you're getting. Then you can run the replacer function as the second argument to JSON.stringify() to check for and discard circular references.

document.querySelectorAll('iframe').forEach(iframe => iframe.remove());

let cache = [];
const globals = JSON.stringify(window, (key, value) => {
  if (typeof value === 'object' && value !== null) {

    // Circular reference found, discard key
    if (cache.indexOf(value) !== -1) return;
      
    // Store value in our collection
    cache.push(value);
  }

  return value;
});

cache = null; // Enable garbage collection
console.log(globals);
docta_faustus
  • 2,383
  • 4
  • 30
  • 47