不能得到一个简单的Chrome通知工作

Can't get a simple Chrome Notification to work

本文关键字:简单 Chrome 通知 工作 一个 不能      更新时间:2023-09-26

我试图通过点击一个按钮来弹出一个简单的Chrome通知,由于某种原因,我得到了一个错误。下面是Javascript部分:

    $('#notification').click(function () {
        var opt = {
            TemplateType: "basic",
            title: "Just a test!",
            message: "Let's see if it works",
            iconUrl: "icon.png"
        }
        chrome.notifications.create('notify', opt, function () { });
});

HTML部分:

    <input id="notification" type="submit" value="Get Notification!" />

和舱单:

{
"manifest_version": 2,
"name": "SimpleNotification",
"description": "Just a notification",
"version": "1.0",
"browser_action": {
    "default_icon":"icon.png",
    "default_popup":"popup.html"
},
"options_page" : "options.html",
"background": {
    "scripts" : ["eventPage.js"],
    "persistent" : false
},
"permissions" : [
    "storage",
    "notifications",
    "contextMenus"
]

}

当试图运行时,我得到:

Uncaught TypeError: Cannot read property 'create' of undefined

提前感谢!

你在哪里调用chrome.notifications?这只能从扩展(后台)调用。你可以这样做,通过消息传递到后台脚本。

的例子:

//contentScript.js
var opt = {
    TemplateType: "basic",
    title: "Just a test!",
    message: "Let's see if it works",
    iconUrl: "icon.png"
};
chrome.runtime.sendMessage({type: "shownotification", opt: opt}, function(){});
//background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if(request.type === "shownotification"){
        chrome.notifications.create('notify', request.opt, function(){})
    }
});

显然代码是正确的。我试图用Chrome运行页面,而不是作为扩展。去图…