在应用内浏览器中无法使用onhashchange (Facebook, Twiiter)

问题描述 投票:1回答:1

我用的是 切换窗口事件 来检测 我的单页应用. 这样我就可以启动AJAX,同时保留浏览器的历史记录。

  1. 用户点击 href="#hashlink "的锚点。
  2. onhashchange检测URL更新。
  3. #hashlink被提取出来并作为AJAX网址(partialshashlink.php)传入。

我发现了一个问题。你可能已经意识到了,但Facebook和Twitter已经开始在应用内浏览器中启动外部链接。它似乎阻止了页面锚点href的默认操作,这已经杀死了我的哈希变化检测。因此,我的web应用几乎没有用处 :-(

Facebook和Twitter的应用内浏览器是最近才发布的,所以要找到一个解决方案是很困难的。

先谢谢你

javascript ajax facebook twitter
1个回答
0
投票

我知道这是一个老问题,但我昨天遇到了同样的问题。我无法找到一个解决方案,允许我保留哈希链接和onhashchange事件的使用。我重写了我的代码,使用 历史API,也就是 广泛支持 caniuse说,除了Opera Mini之外,它适用于所有的浏览器,但当我测试时,它也适用于我)。

一步一步来。

  1. 把所有的哈希链接都变成按钮,或者其他可访问的格式(带有role="link "属性的div,等等)。(如果按钮不包含明确说明其功能的文本,不要忘了包含一个aria-label属性)。

    <button class="nav__list-item" data-id="${p.websafeHandle}" aria-label="Read our Q & A with ${p.name}">
        <div class="nav__list-item__img" style="background-image: url(${p.thumbnail})"></div>
        <span class="nav__list-item__handle">${p.handle}</span>
    </button>
    
  2. 添加点击事件监听器

    const qaLinks = document.querySelectorAll('.nav__list-item')
    qaLinks.forEach(link => {
        link.addEventListener('click', (e) => this.loadQA(e.currentTarget.dataset.id, true))
    })
    
  3. 点击事件处理程序来更新页面内容和浏览器历史记录。

    loadQA(person, updateHistory) {
        // I'm condensing/summarizing the parts of my code that deal with fetching data and
        // outputting it on the page, because it's not particularly relevant to this question. 
        const data = this.data[person]
        this.container.innerHTML = template(Templates.qaPage, data.qa)
    
        // the loadQA function will also be called if somebody comes to this page 
        // with a hash link like the one below. in that case (on an initial visit, 
        // instead of navigation within my single-page app), I wouldn't want to add 
        // the page to the history again, thereby creating a double entry, 
        // which is why I have the updateHistory param
        if (updateHistory) {
            // update our page title and our URL and add it to the browser history
            const title = `MTI - ${data.info.name}`
            const hash = `#/qa/${data.info.websafeHandle}`
            history.pushState(null, title, hash)
        }
    }
    
  4. 每当有人使用浏览器的转发按钮时就会触发的事件处理程序。

    window.addEventListener('popstate', () => this.loadPage())
    
  5. 在popstate事件处理程序中(也是在初始页面加载时运行),获取URL哈希值并相应地加载页面。

    loadPage() {
        if (!window.location.hash) {
            // the param here is for updateHistory
            this.showLanding(false)
        } else {
            const person = this.getHashParam()
            person ? this.loadQA(person, false) : this.showLanding(true)
        }
    }
    

附注:我发现 此应用程序 对我在Facebook的IAB中测试本地代码非常有帮助。你给它一个链接(比如到你的开发网站),它就会生成一个链接(你必须使用xip.io的链接才能在FB中打开),给你一个二维码让你用手机扫描,它将你的手机连接到它的开发工具,并在你的浏览器中打开该链接。然后你可以复制该链接,将其发布在只有你能看到的FB私人帖子中,然后瞧!你可以在Facebook浏览器中访问你的本地服务器,Ghostlab让你可以访问所有你通常在Chrome中的开发工具。

© www.soinside.com 2019 - 2024. All rights reserved.