8 – Tracking how long it takes a user to submit a node edit form?


For a quiz node, I want to track how long it takes a user to submit a node form (the time from Drupal generating the form until the time that the user presses submit), and I want to store this duration in a field on my node.

Use case

Each node of content type Quiz is a 10 question quiz. I want to track the time that users spend filling out the node in order to track their improvement in speed over time.

I do NOT want to track the time spent on the website in general; for that, I already use Google Analytics with scroll tracking, and there is also the Time Spent module.

What I tried

On my node, I added an Integer field, Duration. My thought was that I could calculate the interval from the timestamp when the form was generated until the time the node was saved by adding code in hook_node_presave():

  $original_time = ??? // How do I get the time when the node form was generated? 
  $current_time = Drupal::time()->getCurrentTime();
  $duration = $current_time - $original_time;

Where I’m stuck is I don’t know how to get the time when the node form was created.

I tried to add a Datetime field to my node with a Default date of Current date, but the current date is not set until the node is saved, so that doesn’t work.

So, how can I track the time from generating a node edit form until the time the user presses submit?