Typescript类型BeforeInstallPromptEvent

Whi*_*her 3 typescript service-worker progressive-web-apps angular

使用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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ZYi*_*nMD 17

对已接受答案的改进:您还需要将密钥添加到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
Run Code Online (Sandbox Code Playgroud)

请注意,这declare global {}是一个用于在代码中输入全局内容的包装器。您还可以在不存在导入/导出关键字的环境文件中执行此操作,然后不需要包装器。但将相关代码放在同一个文件中是一个很好的做法。


kre*_*erd 11

BeforeInstallPromptEvent是非标准的Web API,目前只有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>;

}
Run Code Online (Sandbox Code Playgroud)

  • 现在还是这样吗? (4认同)
  • 不要忘记 ``interface WindowEventMap { "beforeinstallprompt": BeforeInstallPromptEvent; }``` 可能还需要将其放入 `declare global {}` 块中。 (2认同)