javaScript中打开一个新窗口报错Uncaught DOMException: Blocked a frame with origin “null“ from accessing a cross

2023-05-16

javaScript中打开一个新窗口报错Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross

报错原因:跨页面操作涉及域的概念(origin),错误的意思是:未捕获的安全错误:阻止了一个域为null的frame页面访问另一个域为null的页面。代码运行时在本地直接用浏览器打开的,地址栏是file:///的页面,只需改为localhost访问就行。

Window的name属性可设置或返回存放窗口的名称的一个字符串

Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

“document_write()”方法会覆盖页面的问题

JS 中document.write()的用法和清空的原因浅析

案例1

 

案例2

js.html页面代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>javaScript中打开一个新窗口报错window.open</title>
<style type="text/css">
input[type=button] {
	background-color: #8E388E;
	border: 0px solid #8E388E;
	color: #fff;
	width: 160px;
	height: 40px;
	border-radius: 6px; /*把边框做成圆角*/
}

</style>
<script type="text/javascript">

var myWindow = null;
function openWin1() {
	var windowTitle = "测试页面";
	myWindow = window.open('', 'testWindow', 'width=300,height=300');
	setTimeout(function(){
		myWindow.document.write("<p>窗口名称为: " + myWindow.name + "</p>");
		myWindow.document.title = windowTitle;
	}, 2000) ;
}

var myWindow2 = null;
function openWin2() {
	var windowTitle = "测试页面2";
	myWindow2 = window.open('js2.html', 'testWindow2', 'width=500,height=300');
	setTimeout(function(){
/*
w3school的官方说明:您只能在HTML输出中使用document.write。如果您在文档加载后使用该方法,会覆盖整个文档。
避免方法:
1.在onload之前使用document.wriet()方法;
2.避免在onclick()事件中使用,可用console或innerHTML代替
*/
		//document.write()会覆盖掉原来js2.html页面中的内容
// 		myWindow2.document.write("<p>窗口名称为: " + myWindow2.name + "</p>");
		myWindow2.document.getElementById("myDiv").innerHTML = "窗口名称为: " + myWindow2.name;
		myWindow2.document.title = windowTitle;
	}, 1000) ;
}
</script>
</head>
<body style="background-color: #CCE8CF;">
<h2>javaScript中打开一个新窗口报错window.open</h2>
<input type="button" value="打开我的窗口1" onclick="openWin1()" />
<input type="button" value="打开我的窗口2" onclick="openWin2()" />
<div id="div1" style="background-color: Wheat; height: 200px;">
</div>
</body>
</html>

js2.html页面代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>这是一个简单的测试页面哦</title>
</head>
<body>
<h1>这是一个简单的测试页面哦</h1>
<div id="myDiv" style="background-color: #D8BFD8; height: 200px;">
</div>
</body>
</html>

大家可以自己去测试一下!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

javaScript中打开一个新窗口报错Uncaught DOMException: Blocked a frame with origin “null“ from accessing a cross 的相关文章

随机推荐