当您无法控制它时,如何规避相同的原始策略错误

Sab*_*ang 5 javascript error-handling exception try-catch same-origin-policy

我正在尝试使用我不知道的深层次结构来对一个大对象进行字符串化,以便摆脱它的循环引用.除了通常我遇到相同的原始策略异常之外,它大部分都有效.我对引用其他域或其他受限元素的任何子对象不感兴趣.

JSON.parse(stringify(window));
Run Code Online (Sandbox Code Playgroud)

抛出:

Uncaught DOMException: Blocked a frame with origin "http://www.xxxxxx.com" from accessing a cross-origin frame.
Run Code Online (Sandbox Code Playgroud)

如果我无法控制本机JSON.stringify()代码,如何通过优雅地跳过导致它的原因来避免异常并完成代码的执行?

JSON.stringify()这里只是一个例子,我想更普遍的是我要问的是如果你不是试图违反它而是如何在这种情况下处理它而如何规避相同的原始政策例外?

doc*_*tus 1

尝试这个!首先,您需要删除页面上的所有 iframe,以防止出现跨源错误。然后,您可以运行替换函数作为第二个参数来JSON.stringify()检查并丢弃循环引用。

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);
Run Code Online (Sandbox Code Playgroud)

  • 什么时候我们必须删除 iFrame? (2认同)