html:
<iframe id="myFrameId" name="myFrameName" :src="url" height="300" width="500"></iframe>
非跨域刷新:
frameWindow.location.reload()
// 通过各种伎俩获取的iframe window对象都行const frameWindow = document.querySelector('#myFrameId').contentWindow frameWindow.location.reload()
这个办法只能在非跨域时应用。
其实, 非跨域的话,轻易一种办法都能够的。
跨域刷新 (非跨域也能够):
思路:通过从新给iframe的src赋值来刷新
// 办法1const tmpUrl = document.all.myFrameName.srcwindow.open(tmpUrl ,'myFrameName')// 办法2const el = document.querySelector('#myFrameId')const tmpUrl = el.srcel.src = tmpUrl
成果相似但又不齐全相似于location.href = xxx
,不同点 :
- iframe的src 不会随外部跳转而变动,location.href 会随页面跳转而变动。
- 当 iframe 外面齐全没有产生过跳转,且
tmpUrl
带hash时(如https://cn.vuejs.org/v2/guide/installation.html#NPM
带了#NPM
),上述办法就无奈刷新iframe,同样条件下location.href = location.href
能够刷新页面
------以上只是顺带记录一下,轻易冲浪一下都能找到,接下来才是我写这篇笔记的重点! ------
在写这篇笔记的前正好有个需要要刷新带hash的iframe,用上述办法都不行,百度、google了半小时无果,差点自闭
于是跑去摸鱼,刚蹲下就眉头一皱;计上心来 “ 先将src
置成任意与tmpUrl
不一样的链接, 在置回来 ”:
// 办法3 - ❌❌❌, iframe还是不会刷新const el = document.querySelector('#myFrameId')const tmpUrl = el.srcel.src = 'about:blank'el.src = tmpUrl
用这段代码,你会发现并没有达到预期成果。因为事件产生的太快了,iframe它还没反馈过去。那就给iframe一点工夫(setTimeout
)呗
// 办法3 - ⭕⭕⭕const el = document.querySelector('#myFrameId')const tmpUrl = el.srcel.src = 'about:blank' // 作为一个长期的链接,如果是其它失常可拜访URL,会节约一些不必要流量const _t = setTimeout(()=>{ el.src = tmpUrl clearTimeout(_t)}, 300) // 太短,iframe仍然反馈不过去,太长成果又不好,300ms刚刚好
至此,完满解决需要~
总结:遇到难题,摸摸鱼就好~