Skip to content

Instantly share code, notes, and snippets.

@greatghoul
Last active May 6, 2023 00:32
Show Gist options
  • Save greatghoul/614548bfb228b073943299228a26d7f2 to your computer and use it in GitHub Desktop.
Save greatghoul/614548bfb228b073943299228a26d7f2 to your computer and use it in GitHub Desktop.
chrome extension message passing example
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
console.log(`${message} in content1`)
sendResponse(`${message} from content1`)
// setTimeout(() => {
// sendResponse(`${message} from content1`)
// }, 2000)
//
// return true
}
)
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
console.log(`${message} in content2`)
sendResponse(`${message} from content2`)
// setTimeout(() => {
// sendResponse(`${message} from content2`)
// }, 3000)
//
// return true
}
)
{
"name": "Message Passing",
"manifest_version": 2,
"version": "0.1",
"description": "Message Passing Examples",
"browser_action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content1.js", "content2.js"]
}
],
"permissions": [
"tabs"
]
}
<body style="width: 300px; height: 200px;">
<button id="send">Send a message</button>
<div id="result"></div>
<script src="popup.js"></script>
</body>
function appendResult(result) {
document.querySelector('#result').innerHTML += `<p>${result}</p>`
}
function clickHandler(event) {
chrome.tabs.query({ active: true}, tabs => {
chrome.tabs.sendMessage(tabs[0].id, 'hello', result => appendResult(result))
})
}
document.querySelector('#send').addEventListener('click', clickHandler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment