在使用者按下"授權"後, 才跳出警告視窗, 當然也能再次取消(移除)授權.
在一些非核心的功能上採取這樣的方式, 可以減少使用者不必要的擔心.
manifest.json
{
"manifest_version": 2,
"name": "ironman6",
"version": "1.0",
"browser_action": {
"default_popup": "index.html"
},
"optional_permissions": [
"background",
"bookmarks",
"clipboardRead",
"clipboardWrite",
"contentSettings",
"contextMenus",
"cookies",
"debugger",
"history",
"idle",
"management",
"notifications",
"pageCapture",
"tabs",
"topSites",
"webNavigation",
"webRequest",
"webRequestBlocking"
]
}
index.html
<title>ironman6</title>
<meta charset="utf-8">
<style>body {width: 500px;}</style>
<table id="content"></table>
<script src="app.js"></script>
app.js
var permissionsList = [
"background",
"bookmarks",
"clipboardRead",
"clipboardWrite",
"contentSettings",
"contextMenus",
"cookies",
"debugger",
"history",
"idle",
"management",
"notifications",
"pageCapture",
"tabs",
"topSites",
"webNavigation",
"webRequest",
"webRequestBlocking"
];
var output = [];
var content = document.querySelector('#content');
for (var i = 0; i < permissionsList.length; i++) {
var permissions = permissionsList[i];
output.push('<tr class="' + permissions + '">');
output.push('<td>' + permissions + '</td>');
output.push('<td><button data-item="' + permissions + '" class="request">授權</button></td>');
output.push('<td><button data-item="' + permissions + '" class="remove">移除</button></td>');
output.push('</tr>');
}
content.innerHTML = output.join('');
var request = document.querySelectorAll('.request');
var remove = document.querySelectorAll('.remove');
for (var i = 0; i < permissionsList.length; i++) {
var permissions = permissionsList[i];
Contains(permissions);
request[i].addEventListener('click', Request);
remove[i].addEventListener('click', Remove);
}
function Request(){
var item = this.dataset.item;
chrome.permissions.request({
permissions: [item]
}, function(granted) {
console.dir(granted);
if (granted) {
document.querySelector('.' + item).style.color = 'blue';
}
});
}
function Remove(){
var item = this.dataset.item;
chrome.permissions.remove({
permissions: [item]
}, function(removed) {
if (removed) {
document.querySelector('.' + item).style.color = '';
}
});
}
function Contains(permissions){
chrome.permissions.contains({
permissions: [permissions]
}, function(result) {
if (result) {
document.querySelector('.' + permissions).style.color = 'blue';
} else {
document.querySelector('.' + permissions).style.color = '';
}
});
}