js拦截并处理所有跳转请求

返回
Author Avatar
钢翼
2024-03-22
编程
51
      const contentWindow = window
      if(contentWindow.open.toString() == 'function open() { [native code] }'){
          const _open = contentWindow.open
          contentWindow.open = function (url) {
            if(url.startsWith("/index.html")){
                _open(url)
            }else{
                _open("/index.html?url="+encodeURIComponent(url))
            }
          }
          contentDocument.body.addEventListener("click",function(event){
            const a = event.target.closest("a")
            if(a){
                event.preventDefault()
                let url = a.getAttribute("href")
                if(url){
                    contentWindow.open(url)
                }
            }
          })
      }

上面代码将原跳转地址改为/index.html?url={url}