JavaScript使用window.open打开新窗口后scrollBy滚动不生效如何解决
问题原因
- 页面加载时序问题:你调用
newwindow.scrollBy(0,400)时,新窗口的页面资源还在加载,DOM结构、内容高度都未完全渲染完成,此时页面可滚动高度小于可视区域高度,滚动操作不会生效。 - 跨域权限限制:如果你打开的目标url和当前站点不属于同域(协议、域名、端口三者任意一个不一致),受浏览器同源策略限制,父窗口没有权限操作新窗口的页面属性,滚动相关的调用会被浏览器直接拦截。
解决方案
同域场景修复
监听新窗口的页面加载完成事件后再执行滚动操作,代码修改如下:
function createPop(url, name) { var newwindow; newwindow=window.open(url,name,'width=760,height=950,toolbar=0,menubar=0,location=0,popup=1,status=0'); if (window.focus) {newwindow.focus()} // 等待新窗口资源全部加载完成后再执行滚动 newwindow.addEventListener('load', function() { newwindow.scrollBy(0,400); }) }
如果部分场景资源加载较慢滚动不生效,可以在load事件里加100ms左右的延时做兜底。
跨域场景修复
父窗口无法直接操作跨域新窗口的属性,需要把滚动参数通过url查询参数或者hash的方式传递给新窗口,由新窗口自身的JS代码读取参数后执行滚动:
- 父窗口拼接参数打开新窗口:
// 把滚动高度拼到url的hash中 function createPop(url, name) { const urlWithScroll = `${url}#scrollHeight=400` var newwindow; newwindow=window.open(urlWithScroll,name,'width=760,height=950,toolbar=0,menubar=0,location=0,popup=1,status=0'); if (window.focus) {newwindow.focus()} }
- 新窗口页面自身添加滚动逻辑:
window.addEventListener('load', function() { // 读取hash中的滚动参数 const scrollVal = new URLSearchParams(window.location.hash.slice(1)).get('scrollHeight') if (scrollVal) { window.scrollBy(0, Number(scrollVal)) } })
内容的提问来源于stack exchange,提问作者JanezKranjski
相关产品推荐
相关产品推荐

