【问题标题】:Chrome doesn't throw an alert box when handling an errorChrome 在处理错误时不会抛出警告框
【发布时间】:2014-04-24 07:51:53
【问题描述】:

以下内容在 Firefox 中正常工作,即当您尝试修改外部文档时会出现警告框。但在 Chrome 中没有警报:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Frame Selector</title>
    <style>
        iframe {
            display: block;
            width: 300px;
            height: 200px;
        }
    </style>
</head>

<body>
    <iframe src="http://dl.dropboxusercontent.com/u/4017788/Labs/frame1.html" id="myFrame"></iframe>
    <select id="selector" onchange="setSRC();">
        <option value="http://dl.dropboxusercontent.com/u/4017788/Labs/frame1.html">Frame 1</option>
        <option value="http://dl.dropboxusercontent.com/u/4017788/Labs/frame2.html">Frame 2</option>
        <option value="http://www.example.com/">Frame 3</option>
    </select>
    <button type="button" id="btn" onclick="ChangeColor();">Change color!</button>
    <script>
        var myFrame = document.getElementById('myFrame');

        function setSRC() {
            myFrame.src = document.getElementById('selector').value;
        }

        function ChangeColor() {
            if (myFrame.contentDocument) {
                myFrame.contentDocument.body.style.backgroundColor = 'green';
            } else {
                alert('You cannot modify a document on a different domain!');
            }
        }
    </script>
</body>

</html>

这是demo
什么原因?什么是跨浏览器解决方案?

【问题讨论】:

  • 这是什么意思,不是“正确”?
  • 它不显示警报。
  • 我在 Firefox 和 Chrome 中都没有警报。
  • 刚刚编辑过。对不起!
  • 正确是什么意思?什么,具体来说,不能在 Chrome/其他浏览器上运行?具体一点。

标签: javascript html iframe error-handling same-origin-policy


【解决方案1】:

使用try/catch 捕获该安全错误:

    function ChangeColor() {
        try {
            myFrame.contentDocument.body.style.backgroundColor = 'green';
        } catch(e) {
            alert('You cannot modify a document on a different domain!');
        }
    }

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多