如何在 chrome 扩展中使用 chrome.notifications 请求权限
How to request permission with chrome.notifications in chrome extension
我想在我的扩展程序中使用 chrome.notifications
。当我加载解压我的扩展程序时,我注意到只要转到扩展程序页面,我就已经获得了使用通知的权限。
不应该有一个提示询问用户使用通知的权限吗?我的计划是为用户提供允许或禁止扩展通知的选项。这个问题影响了我的计划,包括一个按钮,该按钮将要求用户获得通知权限。
manifest.json
{
"manifest_version": 2,
"name": "",
"version": "",
"description": "",
"icons": {
"16": "",
"48": "",
"128": ""
},
"browser_action": {
"default_title": "",
"default_icon": "",
"default_popup": "html/popup.html"
},
"author": "",
"background": {
"scripts": [
"js/background.js"
],
"persistent": false
},
"chrome_url_overrides": {
"newtab": "html/index.html"
},
"incognito": "not_allowed",
"permissions": [
"activeTab",
"alarms",
"contextMenus",
"notifications",
"storage"
],
"short_name": ""
}
我这样做是为了检查通知的用户权限
console.log("Request notifications");
chrome.notifications.getPermissionLevel(function (result) {
console.log(result); // this returns granted
});
感谢@wOxxOm,我发现了 permissions
的文档,并且我能够选择性地允许用户通过此代码片段启用 notifications
。
getNotificationPermission() {
chrome.permissions.request(
{
permissions: ["notifications"],
},
function (granted) {
if (granted) {
// do this
} else {
// do that
}
}
);
},
除此之外,我还必须在 manifest.json 中添加 optional_permissions
键。
manifest.json
"optional_permissions":["notifications"],
我想在我的扩展程序中使用 chrome.notifications
。当我加载解压我的扩展程序时,我注意到只要转到扩展程序页面,我就已经获得了使用通知的权限。
不应该有一个提示询问用户使用通知的权限吗?我的计划是为用户提供允许或禁止扩展通知的选项。这个问题影响了我的计划,包括一个按钮,该按钮将要求用户获得通知权限。
manifest.json
{
"manifest_version": 2,
"name": "",
"version": "",
"description": "",
"icons": {
"16": "",
"48": "",
"128": ""
},
"browser_action": {
"default_title": "",
"default_icon": "",
"default_popup": "html/popup.html"
},
"author": "",
"background": {
"scripts": [
"js/background.js"
],
"persistent": false
},
"chrome_url_overrides": {
"newtab": "html/index.html"
},
"incognito": "not_allowed",
"permissions": [
"activeTab",
"alarms",
"contextMenus",
"notifications",
"storage"
],
"short_name": ""
}
我这样做是为了检查通知的用户权限
console.log("Request notifications");
chrome.notifications.getPermissionLevel(function (result) {
console.log(result); // this returns granted
});
感谢@wOxxOm,我发现了 permissions
的文档,并且我能够选择性地允许用户通过此代码片段启用 notifications
。
getNotificationPermission() {
chrome.permissions.request(
{
permissions: ["notifications"],
},
function (granted) {
if (granted) {
// do this
} else {
// do that
}
}
);
},
除此之外,我还必须在 manifest.json 中添加 optional_permissions
键。
manifest.json
"optional_permissions":["notifications"],