在VUE内使用beforeinstallprompt接口安装PWA添加到桌面

该文章已生成可运行项目,

前提是先在网站根目录下配置一个 “manifest.json” 文件,内容大致如下:

{
    "name": "Your App Name",
    "display_override": ["window-controls-overlay"],
    "short_name": "Short Name",
    "orientation": "any",
    "description": "App Description",
    "start_url": "xxx.html",
    "scope": "./",
    "display": "fullscreen",
    "background_color": "#000000",
    "theme_color": "#000000",
    "icons": [
        {
            "src": "icon-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "icon-256x256.png",
            "sizes": "256x256",
            "type": "image/png"
        },
        {
            "src": "icon-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ],
    "screenshots": [
        {
            "src": "screenshot.jpg",
            "sizes": "640x300",
            "type": "image/jpg"
        }
    ],
    "shortcuts": [
        {
            "name": "Home",
            "url": "xxx.html",
            "icons": [{ "src": "shortcuts.png", "sizes": "16x16" }]
        }
    ],
}

然后在html页面的head头部配置信息(记得一定要有manifest.json):

<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" content="#000000" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-title" content="Your App Name" />
<link rel="apple-touch-icon" href="icon-192x192.png" />

接下来可以先参照MDN的官方教程:

https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeinstallprompt_event

当浏览器检测到某个网站可以进行 installed as a Progressive Web App 时,将触发 beforeinstallprompt 事件。

第一步:先增加一个button按钮

<button id="install" hidden>Install</button>

第二步,用js监听事件

  • 当浏览器检测到页面符合 PWA 安装条件时,会触发 beforeinstallprompt 事件。可以监听此事件并保存触发它的对象,以便在适当的时机调用。
  • 然后在合适的业务逻辑中(例如点击安装按钮)调用 prompt() 显示安装弹窗。
  • 通过清除 installPrompt 变量并再次隐藏自身来重置其状态。
let installPrompt = null;
const installButton = document.querySelector("#install");

window.addEventListener("beforeinstallprompt", (event) => {
  event.preventDefault();
  installPrompt = event;
  installButton.removeAttribute("hidden");
});

installButton.addEventListener("click", async () => {
  if (!installPrompt) {
    return;
  }
  const result = await installPrompt.prompt();
  console.log(`Install prompt was: ${result.outcome}`);
  installPrompt = null;
  installButton.setAttribute("hidden", "");
});

如果在VUE中使用,那么需要用以下方法

  1. 增加Vue的 created 或 onBeforeMount 生命周期函数,beforeinstallprompt 监听方法只能写在 created(或onBeforeMount) 内,mounted方法不管用。
  2. 提前设置变量接收监听事件返回对象,用来按钮点击时的操作
  3. 单独为按钮增加点击时的响应事件
created() {
	window.addEventListener("beforeinstallprompt", (event) => {
	    event.preventDefault()
	    // 提前设置一个变量接收监听对象
	    this.installPrompt = event
	    // 提前设置一个开关用来隐藏显示安装按钮
	    this.isShowInstallButton = true
	})
}

// 安装PWA应用
onInstallApp() {
    if (!this.installPrompt) {
        return
    }
    this.installPrompt.prompt().then(result => {
        this.disableInAppInstallPrompt();
        console.log(`Install prompt was: ${result.outcome}`);
    });
},
// 卸载事件隐藏安装按钮
disableInAppInstallPrompt() {
    this.installPrompt = null;
    this.isShowInstallButton = false
}

或使用组合式API

const { createApp, ref, reactive, computed, onMounted, onBeforeMount } = Vue
createApp({
	setup() {
		// 安装应用按钮
        const installPrompt = ref(null)
        const isShowInstallButton = ref(false)

		// 安装PWA应用
        function onInstallApp() {
            if (!installPrompt.value) {
                return
            }
            installPrompt.value.prompt().then(result => {
                disableInAppInstallPrompt()
                console.log(`Install prompt was: ${result.outcome}`)
            });
        }
        function disableInAppInstallPrompt() {
            installPrompt.value = null;
            isShowInstallButton.value = false
        }
        
		onBeforeMount(() => {
            window.addEventListener("beforeinstallprompt", (event) => {
                event.preventDefault()
                installPrompt.value = event
                isShowInstallButton.value = true
            })
        })
		return {isShowInstallButton, onInstallApp}
	}
}).mount('#App')
<button v-show="isShowInstallButton" @click="onInstallApp()">添加到桌面</button>
本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值