[10] chrome 扩展开发 - 运行时申请用户权限
一、说明
chrome 扩展程序的原则之一便是最小权限,如果涉及到用户的隐私,则必须谨慎使用用户权限。
收集和传输任何用户数据的扩展程序必须符合用户隐私政策。
隐私政策地址:https://developer.chrome.com/webstore/program_policies#userdata
二、减少使用的权限
并不是声明越多权限越好,manifest 中配置 permissions
字段必须声明扩展程序使用的权限,如果一个扩展程序启动时并不需要依赖某个权限,则不需要再 permissions
中声明,这种权限声明成 optional_permissions
更合适。
1、activeTab
当用户使用扩展程序时,activeTab
权限才会授予对当前活动 tab 的扩展程序临时访问权限,当用户导航离开或关闭当前选项卡时,访问权限将被切断。
它可以作为 <all_urls>
的许多用途的替代品。
{
"name": "Very Secure Extension",
"version": "1.0",
"description": "Example of a Secure Extension",
"permissions": ["activeTab"],
"manifest_version": 2
}
activeTab
权限在安装期间不显示警告消息。
三、使用 Optional Permission
optional_permission
能够让用户选择是否授权给扩展程序,如果扩展程序的某个功能对扩展程序的核心功能不是必不可少的,将其设置为可选,并将 API 或域移动到 optional_permissions
字段中。
比如我需要在 https://www.google.com/
域中使用 tabs
权限:
{
"name": "Very Secure Extension",
...
"optional_permissions": [ "tabs", "https://www.google.com/" ],
...
}
如果并不关心域,全部请求权限,则:
{
"permissions": ["storage", "declarativeContent", "contextMenus"],
"optional_permissions": [ "tabs"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action":{
"default_popup": "popup.html"
},
}
请求权限
button.onclick = () => {
console.log('asd');
chrome.permissions.request({
permissions: ['tabs'],
}, (granted) => {
if (granted) {
alert('request permission Success!');
} else {
alert('request permission Failed!');
}
})
}
结果:
移除权限
button2.onclick = () => {
console.log('asd');
chrome.permissions.remove({
permissions: ['tabs'],
}, (granted) => {
if (granted) {
alert('remove permission Success!');
} else {
alert('remove permission Failed!');
}
})
}
完整代码
仓库地址:https://github.com/postbird/chrome-extensions-demo/tree/master/demo8-userPrivacy
文章版权:Postbird-There I am , in the world more exciting!
本文链接:http://www.ptbird.cn/chrome-extensions-user-privacy.html
转载请注明文章原始出处 !
动态申请权限,只能是通过popup来触发吗