xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Beacon API & Page Visibility API & pagehide & Front-End Monitor In Action

Beacon API & Page Visibility API & pagehide & Front-End Monitor In Action

close tab

client

const log = console.log;

log('app init');

const monitorLog = (obj = {}, text = '') => {
  // Test that we have support
  if (!navigator.sendBeacon) {
      // XHR fallback
      const url = 'http://localhost:3000/api/post';
      this.loading = true;
      fetch(url, {
        headers: {
          "Content-Type": "application/json",
        },
        method: "POST",
        // mode: "no-cors",
        mode: "cors",
        cache: "no-cache",
        body: JSON.stringify(obj),
      })
      .then(res => console.log(`res =`, res))
      .catch(err => console.error(`error =`, err))
      .finally(() => {
        this.loading = false;
      });
      // return true;
  } else {
    const url = 'http://localhost:3000/api/beacon';
    // Content-Type: application/x-www-form-urlencoded
    // const data = new FormData();
    // const keys = Object.keys(obj);
    // for (const key of keys) {
    //   data.append(key, obj[key]);
    // }
    // if(text) {
    //   data.append('desc', text);
    // }
    // console.log(`Beacon API 🔥 数据上报 = ${JSON.stringify(obj, null, 4)}`);
    const data = new Blob(
      [JSON.stringify(obj)],
      {type : 'application/json'}
    );
    navigator.sendBeacon(url, data);
  }
};




server



app.post('/api/post', (req, res) => {
  console.log('\npost req.body =', req.body);
    // console.log('post req', req);
    // console.log('post req', req.params, req.query);
    res.setHeader('Content-Type', 'application/json');
    // res.sendStatus(200);
    res.send({res: 'post api'});
});

app.post('/api/beacon', (req, res) => {
  console.log('\nbeacon req.body =', req.body);
  // console.log('beacon req', req);
  // console.log('beacon', req.params, req.query);
  res.setHeader('Content-Type', 'application/json');
  // res.sendStatus(200);
  res.send({res: 'beacon api'});
});

demo

steps

  1. run the express server

  2. open the URL http://localhost:3000/

  3. close the tab

  4. check the logs

refs

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

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

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

page-lifecycle-api

https://developers.google.com/web/updates/2018/07/page-lifecycle-api#developer-recommendations-for-each-state

https://github.com/GoogleChromeLabs/page-lifecycle

https://developers.google.com/web/updates/images/2018/07/page-lifecycle-api-state-event-flow.png

Back/forward cache

https://web.dev/bfcache/

window.addEventListener('pagehide', function(event) {
  if (event.persisted === true) {
   console.log('This page *might* be entering the bfcache.');
  } else {
    console.log('This page will unload normally and be discarded.');
  }
});



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-04-27 14:08  xgqfrms  阅读(74)  评论(4编辑  收藏  举报