Search code examples
javascripthtmliframeerror-handlingsame-origin-policy

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


The following works properly in Firefox, i.e. 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?


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!');
            }
        }