最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I implement 'Add to homescreen button' in a React app? - Stack Overflow

programmeradmin1浏览0评论

I have a deployed app with a secure connection (https).
I managed to add it to my android home screen using this feature in Google Chrome:

The problem is that users aren't likely to do this if I don't add a button that does that in the app.

After a bit of research, I tried to adapt the code here to my React app.
So I transformed this:

let deferredPrompt;
const addBtn = document.querySelector(".add-button");
addBtn.style.display = "none";
window.addEventListener("beforeinstallprompt", (e) => {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  // Update UI to notify the user they can add to home screen
  addBtn.style.display = "block";

  addBtn.addEventListener("click", (e) => {
    // hide our user interface that shows our A2HS button
    addBtn.style.display = "none";
    // Show the prompt
    deferredPrompt.prompt();
    // Wait for the user to respond to the prompt
    deferredPrompt.userChoice.then((choiceResult) => {
      if (choiceResult.outcome === "accepted") {
        console.log("User accepted the A2HS prompt");
      } else {
        console.log("User dismissed the A2HS prompt");
      }
      deferredPrompt = null;
    });
  });
});  

To this:

export class AddToHomeScreenButton extends Component {
  constructor() {
    super();
    this.state = {
      deferredPrompt: null,
    };
    this.onClick = this.onClick.bind(this);
  }
  componentDidMount() {
    let deferredPrompt;

    window.addEventListener("beforeinstallprompt", (e) => {
      console.log(
        "
发布评论

评论列表(0)

  1. 暂无评论