以下在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 什么原因?什么是跨浏览器解决方案?
答案 0 :(得分:1)
使用try/catch
来捕获该安全错误:
function ChangeColor() {
try {
myFrame.contentDocument.body.style.backgroundColor = 'green';
} catch(e) {
alert('You cannot modify a document on a different domain!');
}
}