Skip to content

Instantly share code, notes, and snippets.

@ngbrown
Created February 15, 2023 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngbrown/e67894d87e5298556afae180c591afef to your computer and use it in GitHub Desktop.
Save ngbrown/e67894d87e5298556afae180c591afef to your computer and use it in GitHub Desktop.
CSP Nonce by extension
async function getCurrentTab() {
let queryOptions = { active: true, lastFocusedWindow: true };
// `tab` will either be a `tabs.Tab` instance or `undefined`.
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}
function reddenPage() {
document.body.style.backgroundColor = 'red';
const nonce = [...document.getElementsByTagName("script")].find(x => x.nonce)?.nonce;
console.log(nonce ?? "no scripts with nonce");
// doesn't work in manifest v3
//const script = document.createElement("script");
//script.setAttribute('nonce', nonce);
//script.innerHTML = "window.alert('hi');";
//document.body.appendChild(script);
}
chrome.action.onClicked.addListener((tab) => {
if(!tab.url.includes("chrome://")) {
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: reddenPage
});
}
});
chrome.webRequest.onResponseStarted.addListener((details) => {
const cspHeaders = details.responseHeaders.filter(x => x.name.toLowerCase()==='content-security-policy');
if (cspHeaders.length > 0){
console.log(JSON.stringify({url: details.url, responseHeaders: cspHeaders}))
}
},
{urls: ["http://localhost/*"]},
["responseHeaders", "extraHeaders"]);
{
"name": "Page Redder",
"action": {},
"manifest_version": 3,
"version": "0.1",
"description": "Turns the page red when you click the icon",
"permissions": [
"activeTab",
"scripting",
"webRequest"
],
"host_permissions": [
"http://localhost/"
],
"background": {
"service_worker": "background.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment