Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Chrome Extension messaging demo modeled after the TCP/IP handshake (SYN, SYN-ACK, ACK)
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
// Start synchronizaiton on browser action click
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('Handshake initiated: BG sending SYN');
chrome.tabs.sendMessage(tab.id, { type: 'bg-syn' });
});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
switch (message.type) {
case 'content-syn':
console.log('Handshake initiated: BG recived SYN (initated by CS)')
console.log('Handshake step: BG sending ACK and requesting SYN (initated by CS)');
chrome.tabs.sendMessage(sender.tab.id, { type: 'bg-syn-ack' });
break;
case 'content-syn-ack':
console.log('Handshake step: BG recieved ACK and SYN request (intiated by BG)');
console.log('Handshake completed: BG sending final ACK (initated by BG)');
chrome.tabs.sendMessage(sender.tab.id, { type: 'bg-ack' });
break;
case 'content-ack':
console.log('Handshake completed: BG recieved final ACK (initated by CS)');
break;
default:
console.log('unknown message type')
break;
}
});
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
// Start synchronizaiton
console.log('Handshake initiated: CS sending SYN');
chrome.runtime.sendMessage({ type: 'content-syn' });
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
switch (message.type) {
case 'bg-syn':
console.log('Handshake initiated: CS recived SYN (initated by BG)')
console.log('Handshake step: CS sending ACK and requesting SYN (initated by BG)');
chrome.runtime.sendMessage({ type: 'content-syn-ack' });
break;
case 'bg-syn-ack':
console.log('Handshake step: CS recieved ACK and SYN request (intiated by CS)');
console.log('Handshake completed: CS sending final ACK (initated by CS)');
chrome.runtime.sendMessage({ type: 'content-ack' });
break;
case 'bg-ack':
console.log('Handshake completed: CS recieved final ACK (initated by BG)');
break;
default:
console.log('unknown message type')
break;
}
});
{
"name": "Messaging demo",
"version": "1.0",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistant": false
},
"content_scripts": [{
"matches": ["*://*/*"],
"js": ["content.js"]
}],
"browser_action": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.