Skip to content

Instantly share code, notes, and snippets.

@kumavis
Last active November 14, 2019 13:45
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 kumavis/5b428fb8ae6dc1e8c3b717155ba08c45 to your computer and use it in GitHub Desktop.
Save kumavis/5b428fb8ae6dc1e8c3b717155ba08c45 to your computer and use it in GitHub Desktop.
WebExtension Manifest v3
// // Called when the user clicks on the browser action.
// chrome.action.onClicked.addListener(function(tab) {
// // No tabs or host permissions needed!
// console.log('Turning ' + tab.url + ' red!');
// // chrome.tabs.executeScript({
// // code: 'document.body.style.backgroundColor="red"'
// // });
// });
chrome.alarms.create({delayInMinutes: 1/60});
chrome.alarms.onAlarm.addListener(function() {
console.log('hello')
});
// self.addEventListener('install', function(event) {
// console.log('sw install')
// });
// self.addEventListener('activate', function(event) {
// console.log('sw activate')
// });
// chrome.action.setBadgeText({ text: `hi` })
const secret = Math.random()
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
sendResponse({ secret });
});
console.log('yott')
// code to be injected into inpage
const code = function () {
function randomFromList(list) {
return list[Math.floor(list.length * Math.random())]
}
function randomColor() {
return randomFromList(['orange', 'pink', 'lime'])
}
function setRandomColor() {
if (!document.body) return
document.body.style.backgroundColor = randomColor()
}
setTimeout(setRandomColor, 20)
setInterval(setRandomColor, 10000)
}
// injection (copied from metamask)
injectScript(`(${code})()`)
function injectScript (content) {
try {
const container = document.head || document.documentElement
const scriptTag = document.createElement('script')
scriptTag.setAttribute('async', false)
scriptTag.textContent = content
container.insertBefore(scriptTag, container.children[0])
container.removeChild(scriptTag)
} catch (e) {
console.error('MetaMask script injection failed', e)
}
}
let latestId = null
function pingBackground() {
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
if (latestId === null) latestId = response.secret
if (latestId === response.secret) return
latestId = response.secret
console.log('sw restarted!')
});
}
setInterval(pingBackground, 100)
{
"name": "Page Redder",
"description": "Make the current page red",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"file://*/*",
"http://*/*",
"https://*/*"
],
"js": [
"contentscript.js"
],
"run_at": "document_start",
"all_frames": true
}
],
"manifest_version": 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment