简体   繁体   中英

The Exact time distance from button clicked to when received data to a website

I'm creating a chrome extension. I need to know when a user clicked on a specific button how many mili seconds will take long, to receive that command to website server. I have a web Worker that is connected to that website too. Could I get the exact time when a button clicked to when data received by website's server? It doesn't matter how many mili seconds take that the respond back to me, the time of receiving request to server after click is mu issue now. can someone help me please?

I'm looking for javascript code to get the time distance between button clicked and received that by website's server.

It is easy to get the time when button is clicked by finding that button and attaching an event handler on it, that calls performance.now()

const t0 = 0;
document.getElementById('buttonId').addEventListener('click',() => {
  t0 = performance.now();
});

Detecting when the server response is received is not trivial. You might need to use the chrome.webRequest api.

Alternatively, a simpler way would be to look for side-effects of the request, that happen in the DOM. (A loader appearing and disappearing, data rows appearing, button being disabled and re-enabled, etc).

You can either poll for these changes, or use the mutationObserver api to detect when elements containing expected attributes are available in the DOM.

Let's say you are polling for the button being re-enabled, every 10ms:

const t1 = 0;
const interval = window.setInterval(() => {
  if (!document.getElementById('buttonId').getAttribute('disabled')) {
    t1 = performance.now();
    requestTime = t1 - t0;
    console.log(requestTime);
    window.clearInterval(interval);
  }
},10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM