如何在Javascript中对弹出窗口使用resizeBy()?遇本地跨域问题
解决Opera GX中window.open打开本地页面后resizeBy无效的跨域问题
问题描述
本地创建help.html页面,通过window.open()弹出后,在Opera GX浏览器中调用resizeBy()无效果,控制台返回跨域错误:
Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
at dimension (file:///C:/Users/R/Documents/CODE/Javascript4/index.html:20:13)
at HTMLButtonElement.onclick (file:///C:/Users/R/Documents/CODE/Javascript4/index.html:10:32)
使用的代码如下:
<button onclick="visitar()">Abrir</button> <button onclick="dimension()">Redimensionar</button> <script> var ventana; function visitar(){ ventana = window.open("help.html", "_blank", "width=500, height=300"); }; function dimension(){ ventana.resizeBy(250, 250); }; </script>
当将页面地址留空时window.open("", "_blank", "width=500, height=300"),resizeBy()有效,但不符合业务需求。
解决方法
方法1:通过本地HTTP服务器运行文件(推荐)
本地直接打开file://协议的文件时,浏览器会将其标记为origin: null,触发同源策略限制。用本地服务器托管文件后,所有页面会处于同一源下,即可正常调用resizeBy()。
- 用Python启动本地服务器:
- Python 3:在项目目录打开终端,执行
python -m http.server 8000 - Python 2:执行
python -m SimpleHTTPServer 8000
- Python 3:在项目目录打开终端,执行
- 然后通过
http://localhost:8000/index.html访问页面,此时help.html和主页面同源,resizeBy()可正常工作。
方法2:使用postMessage跨窗口通信(无需服务器)
如果无法使用本地服务器,可通过postMessage让子窗口自行调整尺寸,避免直接跨域操作子窗口对象:
- 修改主页面脚本,发送尺寸调整指令:
<button onclick="visitar()">Abrir</button> <button onclick="dimension()">Redimensionar</button> <script> var ventana; function visitar(){ ventana = window.open("help.html", "_blank", "width=500, height=300"); }; function dimension(){ // 向子窗口发送调整尺寸的消息 ventana.postMessage({type: 'resize', width: 250, height: 250}, '*'); }; </script>
- 在
help.html中添加监听脚本,接收消息后调整自身尺寸:
<script> window.addEventListener('message', function(event) { if (event.data.type === 'resize') { window.resizeBy(event.data.width, event.data.height); } }); </script>
方法3:临时修改Opera GX安全设置(不推荐)
可以修改浏览器设置关闭本地文件的同源限制,但会降低安全性,仅适合临时测试:
- 右键Opera GX快捷方式,选择「属性」
- 在「目标」栏末尾添加
--allow-file-access-from-files - 重启浏览器后,本地
file://协议的文件可跨域操作,但注意不要用此方式浏览其他网站。
内容的提问来源于stack exchange,提问作者KuroMiki77
相关产品推荐
相关产品推荐

