前端代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>navigator.sendBeacon</title>
</head>

<body>
    <h3>navigator.sendBeacon</h3>
    <div id="time"></div>
</body>
<script>
    const date = new Date()
    document.getElementById('time').innerHTML = date
    window.addEventListener('unload', logData, false);

    function logData() {
        const blob = new Blob(
            [JSON.stringify({
                asdasd: "asdasd",
                uuid: uuid(),
                time: new Date()
            })],
            { type: 'application/json' }
        );
        const joinedQueue = navigator.sendBeacon('/api/user-exit-time', blob);
        console.log('用户代理把数据加入传输队列' + (joinedQueue ? '成功' : '失败'));
    }

    function uuid() {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        const txt = 'test'
        ctx.fillText(txt, 10, 10)
        return canvas.toDataURL()
    }
</script>

</html>

后端代码

const koa = require('koa')
const koaBody = require('koa-body')
const koaRouter = require('koa-router')
const app = new koa()
app.use(koaBody())
const router = new koaRouter({
    prefix: '/api'
})
router.post('/user-exit-time', async (ctx) => {
    console.log(ctx.request.body);
    ctx.body = {
        code: 200
    }
})
app.use(router.routes(), router.allowedMethods())
app.listen(3000, () => {
    console.log('server is running at port 3000')
})
最后修改日期: 2024年 4月 1日

作者

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。