Skip to content

Instantly share code, notes, and snippets.

@dotproto
Created January 11, 2021 23:37
Show Gist options
  • Save dotproto/7dd0da16a67dcba948c647fd2b698bf9 to your computer and use it in GitHub Desktop.
Save dotproto/7dd0da16a67dcba948c647fd2b698bf9 to your computer and use it in GitHub Desktop.
Basic example of requesting optional broad host permissions
// Copyright 2019 Google LLC.
// SPDX-License-Identifier: Apache-2.0
chrome.runtime.onInstalled.addListener(({reason}) => {
console.log(reason);
console.log(chrome.runtime.OnInstalledReason.UPDATE);
if (reason === chrome.runtime.OnInstalledReason.INSTALL ||
reason === chrome.runtime.OnInstalledReason.UPDATE) {
chrome.tabs.create({url: 'popup.html'});
}
})
{
"name": "Debug - Optional Hosts",
"description": "Opens the permission request flow in a popup",
"version": "1.0",
"manifest_version": 2,
"browser_action": {
"default_title": "Opens a new tab.",
"default_popup": "popup.html"
},
"permissions": [],
"optional_permissions": [
"https://*/*"
],
"background": {
"scripts": [
"background.js"
],
"persistent": false
}
}
<!DOCTYPE html>
<html lang="en">
<!--
Copyright 2021 Google LLC.
SPDX-License-Identifier: Apache-2.0
-->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>Open devtools to see events logged</p>
<button id="request">request http://*/*</button>
<button id="remove">remove http://*/*</button>
<script src="popup.js"></script>
</body>
</html>
// Copyright 2021 Google LLC.
// SPDX-License-Identifier: Apache-2.0
let request = document.getElementById('request');
let remove = document.getElementById('remove');
request.addEventListener('click', event => {
chrome.permissions.request({origins: ['https://*/*']}, granted => {
console.log(`Permission granted? ${granted}`);
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
}
});
});
remove.addEventListener('click', event => {
chrome.permissions.remove({origins: ['https://*/*']}, removed => {
console.log(`Permission removed? ${removed}`);
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
}
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment