Skip to content

Commit 52e6b2d

Browse files
committed
Handle reporting by background script for thread safety
Reporting by content scripts can cause race conditions and duplicate reports when multiple tabs are loaded concurrently.
1 parent 292a77c commit 52e6b2d

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

app/scripts/background.js

+24
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { sendReport } from "./study.js";
2+
13
browser.storage.sync.get("ghrOn").then((res) => {
24
if (typeof res.ghrOn == "undefined") {
35
browser.storage.sync.set({
@@ -26,3 +28,25 @@ browser.runtime.onInstalled.addListener(async ({ reason, temporary }) => {
2628
break;
2729
}
2830
});
31+
32+
33+
// Synchronise reporting in background script to avoid
34+
// duplicate reporting by parallel active content scripts
35+
var reportRunning = false;
36+
function manageReporting(message, sender, respond) {
37+
if (message.type != "sendReport") {
38+
return; // message not for us
39+
}
40+
if (reportRunning) {
41+
return; // already triggered by another sender
42+
}
43+
reportRunning = true;
44+
sendReport()
45+
.then(() => respond("done"))
46+
.catch((err) => respond(err))
47+
.finally(() => {
48+
reportRunning = false;
49+
});
50+
return true; // make caller wait for async response
51+
}
52+
browser.runtime.onMessage.addListener(manageReporting);

app/scripts/redact.js

+7-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { DateTime } from "luxon";
2-
import { updateStudyData, sendReport, updateViewCount } from "./study.js";
2+
import { updateStudyData, updateViewCount } from "./study.js";
33
import { toFuzzyDate } from "./fuzzydate.js";
44
import { createPopper } from '@popperjs/core';
55

@@ -657,11 +657,15 @@ function calcDistanceToClosestSibling(el) {
657657
// - log view for study (if opted in)
658658
logViewLoad();
659659

660-
// - send study report if participanting and necessary
660+
// - send study report if participating and necessary
661+
// The actual sending is done by the background script to be
662+
// thread-safe for parallel content script runs
661663
browser.storage.local.get("studyOptIn")
662664
.then((res) => {
663665
if (res.studyOptIn) {
664-
return sendReport();
666+
return browser.runtime.sendMessage(
667+
{ type: "sendReport" }
668+
);
665669
}
666670
})
667671
.catch(error => console.error(error));

0 commit comments

Comments
 (0)