跳到内容

管理 Web 推送通知的用户同意

默认情况下,Pushwoosh SDK 在初始化后会立即显示原生订阅提示。但是,您可能希望在更合适的时间请求用户同意,例如,在用户有机会与您的网站互动之后。

禁用自动订阅

Anchor link to

为了防止 SDK 在初始化时自动显示订阅提示,请在 init 调用中将 communicationEnabled 参数设置为 false。这使您可以控制何时请求推送通知权限。

<script type="text/javascript" src="//cdn.pushwoosh.com/webpush/v3/pushwoosh-web-notifications.js" async></script>
<script type="text/javascript">
var Pushwoosh = Pushwoosh || [];
Pushwoosh.push(['init', {
// other initialization parameters...
communicationEnabled: false, // 禁用通信以防止自动订阅提示
}]);
</script>

在用户同意后启用订阅

Anchor link to

禁用自动订阅后,您可以随时提示用户订阅。当用户同意接收推送通知(例如,通过点击自定义 UI 上的“订阅”按钮)时,您可以通过调用 setCommunicationEnabled 方法来启用通信。

Pushwoosh.setCommunicationEnabled(status?: boolean): Promise<void>

调用 Pushwoosh.setCommunicationEnabled(true) 将启用与 Pushwoosh 服务的通信。启用后,SDK 将继续显示原生浏览器权限提示。

以下是您可能如何使用此方法的示例:

// 假设您有一个 id 为 "subscribe-button" 的订阅按钮
const subscribeButton = document.getElementById('subscribe-button');
subscribeButton.addEventListener('click', () => {
Pushwoosh.setCommunicationEnabled(true)
.then(() => {
console.log('用户已订阅推送通知。');
// 您现在可以隐藏订阅按钮了
subscribeButton.style.display = 'none';
})
.catch((error) => {
console.error('订阅用户时出错:', error);
});
});