如何在浏览器而不是应用程序中强制打开外部链接?

IT技术 javascript reactjs mobile
2021-05-14 20:08:08

我的移动网站提供 YouTube 等外部链接。根据浏览器的不同,它会在网络浏览器或相应的应用程序上打开。

但我想在当前浏览器而不是应用程序中强制打开链接。

示例 - 当我打开像“ https://m.youtube.com这样的链接时,Chrome 移动浏览器总是打开已安装的 Youtube 应用程序

  • 我现在使用 React。
2个回答

这个 2011 年流行的 GitHub Gist(在底部附近的评论中添加了 2018 年的更新代码)用于加载到 WebViews 中的 HTML 文档,但似乎是您所追求的:https ://gist.github.com/kylebarrow/ 1042026

所采用的技术是拦截超链接点击,取消默认的导航(这将导致“打开在YouTube的?”提示出现),并随后又浏览设置window.document.location.assign(这是一样的东西window.location)。我不是 Mobile Safari 专家,但我怀疑如果document.location设置为,Mobile Safari 不会提示在应用程序中打开window.location)。

将此代码放在一个脚本函数中,该函数在文档的 DOM 加载后运行(即DOMContentLoaded或在呈现的 HTML 末尾的内联脚本中)。

    const isMobileSafari = ( ( ua ) => ua.match(/iPad/) || ua.match(/iPhone/) )( window.navigator.userAgent );
    if( isMobileSafari ) {
        const hyperlinks = document.querySelectorAll( 'a:link' );
        for( let anchor of hyperlinks ) anchor.addEventListener( 'click', onHyperlinkClickPreventAppOpen );
    }

    function onHyperlinkClickPreventAppOpen( ev ) {
        const el = ev.target;
        if( el.href && ( el.href.startsWith( "http:" ) || ( el.href.startsWith( "https:" ) ) {
            ev.preventDefault();
            window.document.location.assign( el.href );
        }
    }

如果您想拦截在加载文档后添加的超链接中的点击,请执行以下操作:

document.addEventListener( 'click', onDynamicHyperlinkClickPreventAppOpen );

function onDynamicHyperlinkClickPreventAppOpen ( ev ) {
    const el = ev.target;
    el = el.closest( 'a:link' ); // In case the 'click' event was raised by a descendant of an <a>
    if( !el ) return;

    const fakeEvent = { target: el, preventDefault: ev.preventDefault };
    onHyperlinkClickPreventAppOpen( fakeEvent );
}

启动一个新的快捷方式:Target:"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" https://news.sky.com/ 简单适用于所有浏览器,我是老派的 html。 ...:)