目录

应用开发

工程配置

将Web推送配置中的代码段,复制到您的项目工程中,并在您项目工程的根目录下创建 hms-messaging-sw.js 文件(用来注册Service Worker),该文件内容可以为空。

“hms”为推送服务定义的对象。

申请token

调用getToken方法申请Token。

示例代码:

messaging.getToken().then((currentToken) => {
    if (currentToken) {
        console.log('Get current token');
    } else {
        console.log('No Instance ID token available. Request permission to generate one.');
    }
}).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
});

推送消息

请参见下行消息API进行消息推送。如果是透传消息,则接收消息中字段orignData为透传消息内容。

示例报文:

{
    "validate_only": false,
    "message": {
        "notification": {
            "title": "Big News",
            "body": "This is a Big News!"
        },
        "data": "this is data",
        "webpush": {
            "headers": {
                "ttl": "990",
                "urgency": "NORMAL",
                "topic": "12313"
            },
            "notification": {
                "title": "notification string",
                "body": "web push body",
                "actions": [
                    {
                        "action": "",
                        "icon": "",
                        "title": "string"
                    }
                ],
                "badge": "string",
                "dir": "auto",
                "icon": "string",
                "image": "string",
                "lang": "string",
                "renotify": true,
                "require_interaction": true,
                "silent": true,
                "tag": "string",
                "timestamp": 1545201266,
                "vibrate": [100,200,300]
            },
            "hms_options": {
                "link": "https://example.com"
            }
        },
        "token": [
            "your token1",
            "your token2"
        ]
    }
}

前台接收消息

当浏览器在前台运行时需要实现onMessage回调函数来接收处理消息。

示例代码:

messaging.onMessage((payload) => {
    console.log('Message received.', payload);
});