【问题标题】:How to evade same origin policy error when you have no control over it当您无法控制时如何规避同源策略错误
【发布时间】:2016-01-17 01:09:41
【问题描述】:

我正在尝试对具有我不知道的深层层次结构的大型对象进行字符串化,以摆脱它的循环引用。它在大多数情况下都有效,除了我经常遇到同源策略异常。我对引用其他域或其他受限元素的任何子对象不感兴趣。

JSON.parse(stringify(window));

抛出:

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

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

JSON.stringify() 只是这里的一个例子,我想更一般地说,我要问的是 如果你不想违反它但必须像在这种情况下那样处理它,如何逃避同源策略例外?

【问题讨论】:

  • @buzzsaw 我读过。而是讨论使用允许您跨域资源访问的技术来规避错误的方法,而我试图通过首先不引起错误来避免错误。我不需要跨域访问,甚至不知道哪些引用以及哪些不同的域导致了错误。我只是想跳过和忽略

标签: javascript exception error-handling try-catch same-origin-policy


【解决方案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);

【讨论】:

  • 我们必须删除 iFrame 吗?
猜你喜欢
  • 2011-06-20
  • 2013-09-08
  • 2013-06-27
  • 2011-12-02
  • 2013-11-04
  • 1970-01-01
  • 2011-10-03
  • 2013-05-17
相关资源
最近更新 更多