广州网站排名推广万网域名官网
大致描述
今天上班突然有两个需求,都是关于集成其他系统的需求。
1、跳转至外链的系统
要求点击菜单跳转到别的系统,但是浏览器的标签页只能打开一次,需要监听当前的标签页是否被打开
2、系统中嵌套另一个系统
要求在系统中嵌套另一个系统,但是我们要监听另一个系统的url跳转情况
需求不算难,可能是我经验不多,有些知识点没有想到,现在做完发现挺简单的,但是还得记录下,万一下次还有这样的需求但忘记具体的做法就手麻了。
具体实现
第一个需求
这个需求很简单,就是通过window.open返回的对象来完成功能
// 用来保存新窗口的对象
let _WindowOpenObj = null;window.addEventListener("click",()=>{if(_WindowOpenObj || !_WindowOpenObj.closed()){try{_WindowOpenObj.focus()}catch(e){_WindowOpenObj = window.open("./test.html","_brank")}}else{_WindowOpenObj = window.open("./test.html","_brank")}
})
第二个需求
这里我们主要利用MutationObserver函数完成功能
// 找到iframe标签const iframe = document.getElementById('myIframe');// 使用 MutationObserver 监听 iframe 的 src 属性变化const observer = new MutationObserver((mutations) => {mutations.forEach((mutation) => {if (mutation.type === 'attributes' && mutation.attributeName === 'src') {updateUrlDisplay();}});});observer.observe(iframe, {attributes: true,attributeFilter: ['src']});// 监听 iframe 的 load 事件iframe.addEventListener('load', () => {try {const iframeUrl = iframe.contentWindow.location.href;console.log(iframeUrl,"这是监听到的iframe内的url内容");// 监听 iframe 内部的 history 变化iframe.contentWindow.addEventListener('popstate', updateUrlDisplay);} catch (e) {console.error('无法访问 iframe 内容:', e);}});function updateUrlDisplay() {try {const iframeUrl = iframe.contentWindow.location.href;console.log(iframeUrl,"这是监听到的iframe内的url内容");} catch (e) {console.error('无法获取 iframe URL:', e);}}
感想
以上属于是我个人的小笔记,如果有不对的系统各位大佬和同行们帮忙指出,感谢感谢感谢
同时也希望可以通过这些小笔记帮助同行们解决一时的燃眉之急