Last active
May 6, 2023 00:32
-
-
Save greatghoul/614548bfb228b073943299228a26d7f2 to your computer and use it in GitHub Desktop.
chrome extension message passing example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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" | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body style="width: 300px; height: 200px;"> | |
<button id="send">Send a message</button> | |
<div id="result"></div> | |
<script src="popup.js"></script> | |
</body> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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