简体   繁体   中英

Chrome doesn't throw an alert box when handling an error

The following works properly in Firefox, ie the alert box appears when you try to modify an external document. But in Chrome there's no alert:

<!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>

Here's the demo .
What's the reason? What's a cross browser solution?

Use try/catch to catch that security error :

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

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