Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Created January 6, 2016 14:53
Show Gist options
  • Save ajcrites/7e1ea41659e40e87a517 to your computer and use it in GitHub Desktop.
Save ajcrites/7e1ea41659e40e87a517 to your computer and use it in GitHub Desktop.
function setChildTextNode(elementId, text) {
document.getElementById(elementId).innerText = text;
}
// Tests the roundtrip time of sendRequest().
function testRequest() {
setChildTextNode("resultsRequest", "running...");
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
const start = new Date().getTime();
chrome.tabs.sendMessage(tabs[0].id, {counter: 1}, function handler(response) {
console.log(response);
const counter = response.counter;
if (counter < 1000) {
chrome.tabs.sendMessage(tabs[0].id, {counter}, handler);
} else {
const end = new Date().getTime();
const timer = end - start;
const sec = Math.round(timer / counter);
setChildTextNode("resultsRequest", `${sec} sec`);
}
});
});
}
// Tests the roundtrip time of Port.postMessage() after opening a channel.
function testConnect() {
setChildTextNode("resultsConnect", "running...");
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
const start = new Date().getTime();
const port = chrome.tabs.connect(tabs[0].id);
port.postMessage({counter: 1});
port.onMessage.addListener(response => {
console.log(response);
const counter = response.counter;
if (counter < 1000) {
port.postMessage({counter});
} else {
const end = new Date().getTime();
const timer = end - start;
const usec = Math.round(timer / counter);
setChildTextNode("resultsConnect", `${usec} usec`);
}
});
});
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#testRequest').addEventListener(
'click', testRequest);
document.querySelector('#testConnect').addEventListener(
'click', testConnect);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment