在使用beforeinstallprompt事件时,我应该使用什么样的类型?
我尝试了BeforeInstallPromptEvent类型,但给出了一个错误:
export class PwaService {
//promptEvent: BeforeInstallPromptEvent;
promptEvent;
constructor(private swUpdate: SwUpdate, platform: PlatformService) {
if(platform.isBrowser()){
swUpdate.available.subscribe(event => {
/*if (askUserToUpdate()) {
window.location.reload();
}*/
});
window.addEventListener('beforeinstallprompt', event => {
this.promptEvent = event;
});
}
}
install(): void {
if(this.promptEvent){
this.promptEvent.prompt();
}
}
}发布于 2018-08-14 18:01:57
BeforeInstallPromptEvent是一个非标准的Web,目前只有Chrome和Android支持。我甚至不确定Google是否认为它是稳定的,但在这两种情况下,我都不希望很快在TypeScript DOM库中看到一个正式的类型定义。
但是,您可以自己定义类型,例如在.d.ts文件中。我使用了下面的定义(来自MDN的评论),在Chrome 68中,这个定义似乎足够准确。
/**
* The BeforeInstallPromptEvent is fired at the Window.onbeforeinstallprompt handler
* before a user is prompted to "install" a web site to a home screen on mobile.
*
* @deprecated Only supported on Chrome and Android Webview.
*/
interface BeforeInstallPromptEvent extends Event {
/**
* Returns an array of DOMString items containing the platforms on which the event was dispatched.
* This is provided for user agents that want to present a choice of versions to the user such as,
* for example, "web" or "play" which would allow the user to chose between a web version or
* an Android version.
*/
readonly platforms: Array<string>;
/**
* Returns a Promise that resolves to a DOMString containing either "accepted" or "dismissed".
*/
readonly userChoice: Promise<{
outcome: 'accepted' | 'dismissed',
platform: string
}>;
/**
* Allows a developer to show the install prompt at a time of their own choosing.
* This method returns a Promise.
*/
prompt(): Promise<void>;
}发布于 2021-04-20 01:40:04
对接受的答案的改进:您还需要在WindowEventMap中添加一个密钥
interface BeforeInstallPromptEvent extends Event {
readonly platforms: string[];
readonly userChoice: Promise<{
outcome: "accepted" | "dismissed";
platform: string;
}>;
prompt(): Promise<void>;
}
declare global {
interface WindowEventMap {
beforeinstallprompt: BeforeInstallPromptEvent;
}
}
window.addEventListener("beforeinstallprompt", (e) => {}); // e is now typed注意,declare global {}是一个包装器,用于在代码中键入全局内容。您也可以在不存在导入/导出关键字的环境文件中这样做,然后不需要包装器。但是,将相关代码放在同一个文件中是一个很好的实践。
https://stackoverflow.com/questions/51503754
复制相似问题