【问题标题】:Chrome push NotificationChrome 推送通知
【发布时间】:2016-02-29 07:13:19
【问题描述】:

我正在尝试构建 chrome 推送通知。
我尝试实现从网络引用的随机代码。

代码如下:

notification.html

<script>
    function shows(){

    var notify= webkitNotifications.createNotification('icon48.png','My notification',
    'hi buddy');    
    notify.show();
    }
    if(webkitNotifications){
        setInterval(function()
        {
            shows();
            }, 1000);
    }else{
    chrome.tabs.create({url : "error.html"})
    }

</script>

而在 error.htm

您的扩展程序中有错误

ma​​nifest.JSON

{
    "manifest_version": 2,
    "name": "My Extension",
    "version": "1",
    "description" : "Display every 5 sec",
    "icons" : {"48" :"icon48.png"},
    "permissions" : ["tabs","notifications"],
    "background": {"page": "notifications.html"}
}

问题是扩展程序正在 chrome 中加载,但它不响应代码。也没有显示通知。 :(请帮忙。

【问题讨论】:

    标签: javascript json web google-chrome-extension push-notification


    【解决方案1】:

    我没有使用过 webkitNotifications,但是我使用 chrome.notifications API 实现了 chrome 通知。 我就是这样做的。

    在您的 background.js 中,

    编写一个发送消息的代码。

    function updateValues(){
               var messageString = 'updated';
               chrome.runtime.sendMessage({
                                body : messageString
                            });
    }
    
    updateValues();
    setInterval(updateValues, 10000);
    

    现在添加一个监听器。在频繁更新值的函数之外。

    chrome.runtime.onMessage.addListener(function(msg, sender) {
        var message = msg.body;
    
        chrome.notifications.onClicked.removeListener(openTab);
    
        chrome.notifications.create(getNotificationId(), {
            title : 'Test Update Notification',
            iconUrl : 'notification.png',
            type : 'basic',
            message : message
        }, function(id) {
        });
    
        chrome.notifications.onClicked.addListener(openTab);
    });
    
    function openTab(notificationId) {
       var onClickLink = "http://www.mywebsitenotificationstest.com/";
            chrome.tabs.create({
                url : onClickLink
            });
        }
    
    function getNotificationId() {
        var id = Math.floor(Math.random() * 9007199254740992) + 1;
        return id.toString();
    }
    

    就是这样。

    基本上,当js加载完毕

    1. updateValues() API 被调用并创建一个监听器来调用 每 10 秒更新一次值。
    2. 一旦调用 updateValues,它 使用 sendMessage API。
    3. 在 onMessage 监听器中,我们有代码要创建 使用 chrome.notifications.create 通知。

    就是这样。

    编辑: 我的代码要大得多,我复制粘贴的部分。

    【讨论】:

    • 面临同样的问题。发生的事情是我没有收到任何错误,但我没有收到任何通知。我尝试编辑和实现你的代码..
    • @ChiragKamat 将我建议的脚本保存为 background.js 并将您的 manifest.json 编辑为 "background":{ "scripts":["background.js"] } 这将加载脚本插件的启动。
    • @ChiragKamat 这是否解决了您的通知问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2015-09-13
    • 2016-03-18
    • 2023-03-29
    相关资源
    最近更新 更多