React-js如何触发“ BeforeInstallPromptEvent”以启动“弹出”添加到主屏幕

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

我目前正在开发基于React的应用,并且面临PWA主题。我想触发并显示何时需要允许您将PWA添加到主屏幕的弹出窗口。我最近读到我可以使用BeforeInstallPromptEvent触发它,但是需要遵循一些规则,例如:-该网络应用尚未安装-满足用户参与启发式的要求(当前,用户与域互动至少30秒)-通过HTTPS提供服务(服务工作者需要)-已使用获取事件处理程序注册了服务工作者]

现在我已经具备了所有这些先决条件,但是实际上我无法启动BeforeInstallPromptEvent,所以我从未查看过弹出窗口,有人可以帮助我吗?

下来,您可以找到我以何种方式拦截了此事件

感谢您的建议

window.addEventListener('beforeinstallprompt', function (e) {
    // Prevent Chrome 67 and earlier from automatically showing the prompt
    e.preventDefault()
    // Stash the event so it can be triggered later.
    deferredPrompt = e

    showAddToHomeScreen()
})

function showAddToHomeScreen() {

    var a2hsBtn = document.querySelector(".ad2hs-prompt");

    // @ts-ignore
    a2hsBtn.style.display = "block";

    // @ts-ignore
    a2hsBtn.addEventListener("click", addToHomeScreen);

}

function addToHomeScreen() {  var a2hsBtn = document.querySelector(".ad2hs-prompt");  // hide our user interface that shows our A2HS button
    // @ts-ignore
    a2hsBtn.style.display = 'none';  // Show the prompt
    deferredPrompt.prompt();  // Wait for the user to respond to the prompt
    deferredPrompt.userChoice
    // @ts-ignore
        .then(function(choiceResult){

            if (choiceResult.outcome === 'accepted') {
                console.log('User accepted the A2HS prompt');
            } else {
                console.log('User dismissed the A2HS prompt');
            }

            deferredPrompt = null;

        });}

javascript reactjs progressive-web-apps prompt
1个回答
0
投票

嗨]您是否检查了该事件的平台/浏览器兼容性?compatibility

您可以在此页底部找到它:https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent

仅在我的设备(Android)上的Chrome中触发。在iPhone上不起作用。

当浏览器准备显示默认PWA提示或您可以显示自定义提示时,将触发该事件。我认为这是兼容性问题。

希望,它将对您有帮助

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