Skip to content

The free and privacy-friendly screen recorder with no limits πŸŽ₯

Using tab title in recording + improved recording stability

Alyssa X2e4fbb60dc2b
diff --git a/src/manifest.json b/src/manifest.json
index e7efb86..af826f6 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.2.3",
+ "version": "4.2.4",
"background": {
"service_worker": "background.bundle.js"
},
@@ -116,7 +116,7 @@
"managed_schema": "schema.json"
},
"externally_connectable": {
- "matches": ["https://app.screenity.io/*", "http://localhost:3000/*"]
+ "matches": ["https://app.screenity.io/*"]
},
"optional_permissions": [
"offscreen",
diff --git a/src/pages/AudioOffscreen/index.html b/src/pages/AudioOffscreen/index.html
new file mode 100644
index 0000000..73e90ab
--- /dev/null
+++ b/src/pages/AudioOffscreen/index.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <title>Screenity Audio Offscreen</title>
+ </head>
+ <body>
+ <noscript>This page requires JavaScript.</noscript>
+ </body>
+</html>
diff --git a/src/pages/AudioOffscreen/index.js b/src/pages/AudioOffscreen/index.js
new file mode 100644
index 0000000..3ccc75e
--- /dev/null
+++ b/src/pages/AudioOffscreen/index.js
@@ -0,0 +1,30 @@
+const audioUrl = chrome.runtime.getURL("assets/sounds/beep.mp3");
+let audioEl = null;
+
+const getAudio = () => {
+ if (!audioEl) {
+ audioEl = new Audio(audioUrl);
+ audioEl.volume = 0.5;
+ }
+ return audioEl;
+};
+
+const playBeep = () => {
+ const audio = getAudio();
+ try {
+ audio.currentTime = 0;
+ } catch {}
+ const playPromise = audio.play();
+ if (playPromise?.catch) {
+ playPromise.catch(() => {});
+ }
+};
+
+chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+ if (message?.type === "play-beep-offscreen") {
+ playBeep();
+ if (sendResponse) sendResponse({ ok: true });
+ return true;
+ }
+ return false;
+});
diff --git a/src/pages/Background/listeners/onCommandListener.js b/src/pages/Background/listeners/onCommandListener.js
index 8989cd4..911a30a 100644
--- a/src/pages/Background/listeners/onCommandListener.js
+++ b/src/pages/Background/listeners/onCommandListener.js
@@ -2,6 +2,9 @@ import { sendMessageTab, getCurrentTab } from "../tabManagement";
// Main command listener
export const onCommandListener = () => {
+ let lastToggleDrawingAt = 0;
+ const TOGGLE_DRAWING_COOLDOWN_MS = 400;
+
chrome.commands.onCommand.addListener(async (command) => {
const activeTab = await getCurrentTab();
if (!activeTab || !activeTab.id) return;
@@ -50,6 +53,11 @@ export const onCommandListener = () => {
} else if (command === "stop-recording") {
sendMessageTab(activeTab.id, { type: "stop-recording-tab" });
} else if (command === "toggle-drawing-mode") {
+ const now = Date.now();
+ if (now - lastToggleDrawingAt < TOGGLE_DRAWING_COOLDOWN_MS) {
+ return;
+ }
+ lastToggleDrawingAt = now;
sendMessageTab(activeTab.id, { type: "toggle-drawing-mode" });
} else if (command === "toggle-blur-mode") {
sendMessageTab(activeTab.id, { type: "toggle-blur-mode" });
diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.js
index f0230e9..6d6fcb0 100644
--- a/src/pages/Background/messaging/handlers.js
+++ b/src/pages/Background/messaging/handlers.js
@@ -57,6 +57,30 @@ const API_BASE = process.env.SCREENITY_API_BASE_URL;
const CLOUD_FEATURES_ENABLED =
process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";
+const ensureAudioOffscreen = async () => {
+ if (!chrome.offscreen) return false;
+ try {
+ const contexts = await chrome.runtime.getContexts({});
+ const audioUrl = chrome.runtime.getURL("audiooffscreen.html");
+ const hasAudioOffscreen = contexts.some(
+ (context) =>
+ context.contextType === "OFFSCREEN_DOCUMENT" &&
+ context.documentUrl === audioUrl
+ );
+ if (!hasAudioOffscreen) {
+ await chrome.offscreen.createDocument({
+ url: "audiooffscreen.html",
+ reasons: ["AUDIO_PLAYBACK"],
+ justification: "Play short UI beep sounds.",
+ });
+ }
+ return true;
+ } catch (error) {
+ console.warn("Failed to ensure audio offscreen document", error);
+ return false;
+ }
+};
+
let activeRecordingSession = null;
let recordingTabListener = null;
@@ -953,6 +977,18 @@ export const setupHandlers = () => {
registerMessage("clear-recording-alarm", async () => {
await chrome.alarms.clear("recording-alarm");
});
+ registerMessage("get-tab-id", (message, sender, sendResponse) => {
+ sendResponse({ tabId: sender?.tab?.id ?? null });
+ return true;
+ });
+ registerMessage("play-beep", async (message, sender, sendResponse) => {
+ const ok = await ensureAudioOffscreen();
+ if (ok) {
+ chrome.runtime.sendMessage({ type: "play-beep-offscreen" });
+ }
+ if (sendResponse) sendResponse({ ok });
+ return true;
+ });
registerMessage("refresh-auth", async () => {
if (!CLOUD_FEATURES_ENABLED)
return { success: false, message: "Cloud features disabled" };
diff --git a/src/pages/Background/recording/cancelRecording.js b/src/pages/Background/recording/cancelRecording.js
index 888b541..51947f3 100644
--- a/src/pages/Background/recording/cancelRecording.js
+++ b/src/pages/Background/recording/cancelRecording.js
@@ -16,6 +16,7 @@ export const handleDismiss = async () => {
chrome.action.setIcon({ path: "assets/icon-34.png" });
chrome.runtime.sendMessage({ type: "turn-off-pip" });
+ chrome.storage.local.remove(["recordingMeta"]);
} catch (error) {
console.error("Failed to handle dismiss:", error);
}
@@ -34,6 +35,7 @@ export const cancelRecording = async () => {
focusTab(activeTab);
discardOffscreenDocuments();
chrome.runtime.sendMessage({ type: "turn-off-pip" });
+ chrome.storage.local.remove(["recordingMeta"]);
} catch (error) {
console.error("Failed to cancel recording:", error.message);
}
diff --git a/src/pages/Background/recording/discardRecording.js b/src/pages/Background/recording/discardRecording.js
index 83ae33d..1ec81aa 100644
--- a/src/pages/Background/recording/discardRecording.js
+++ b/src/pages/Background/recording/discardRecording.js
@@ -13,6 +13,7 @@ export const discardRecording = async () => {
sandboxTab: null,
recording: false,
});
+ chrome.storage.local.remove(["recordingMeta"]);
chrome.runtime.sendMessage({ type: "discard-backup" });
chrome.runtime.sendMessage({ type: "turn-off-pip" });
diff --git a/src/pages/Background/recording/startRecording.js b/src/pages/Background/recording/startRecording.js
index 88b99f1..02bcb8e 100644
--- a/src/pages/Background/recording/startRecording.js
+++ b/src/pages/Background/recording/startRecording.js
@@ -10,9 +10,22 @@ export const startRecording = async () => {
const { recordingType } = await chrome.storage.local.get(["recordingType"]);
- if (recordingType === "region") {
+ if (recordingType === "region" || recordingType === "tab") {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tab = tabs[0];
+ if (tab) {
+ const title = tab.title || "";
+ const url = tab.url || "";
+ chrome.storage.local.set({
+ recordingMeta: {
+ type: "tab",
+ title,
+ url,
+ startedAt: Date.now(),
+ },
+ });
+ }
+
if (tab && tab.url) {
try {
const url = new URL(tab.url);
@@ -28,6 +41,8 @@ export const startRecording = async () => {
}
}
});
+ } else {
+ chrome.storage.local.remove(["recordingMeta"]);
}
if (customRegion) {
diff --git a/src/pages/Background/recording/stopRecording.js b/src/pages/Background/recording/stopRecording.js
index cb0e068..fb05120 100644
--- a/src/pages/Background/recording/stopRecording.js
+++ b/src/pages/Background/recording/stopRecording.js
@@ -53,6 +53,7 @@ export const stopRecording = async () => {
if (isSubscribed) {
chrome.alarms.clear("recording-alarm");
discardOffscreenDocuments();
+ chrome.storage.local.remove(["recordingMeta"]);
} else if (hasWebCodecs) {
// Use Mediabunny (editorwebcodecs.html) when WebCodecs is supported
chrome.tabs.create({ url: "editorwebcodecs.html", active: true }, (tab) => {
diff --git a/src/pages/Background/tabManagement/resetActiveTab.js b/src/pages/Background/tabManagement/resetActiveTab.js
index 55c616b..91f1ff2 100644
--- a/src/pages/Background/tabManagement/resetActiveTab.js
+++ b/src/pages/Background/tabManagement/resetActiveTab.js
@@ -13,7 +13,7 @@ export const restartActiveTab = async () => {
sendMessageTab(activeTab.id, { type: "ready-to-record" });
const { countdown } = await chrome.storage.local.get(["countdown"]);
- const delay = countdown ? 3500 : 500;
+ const delay = countdown ? 3120 : 300;
setTimeout(() => {
if (countdown) {
@@ -73,7 +73,7 @@ export const resetActiveTab = async (forceRestart = false) => {
sendMessageTab(targetTabId, { type: "ready-to-record" });
const { countdown } = await chrome.storage.local.get(["countdown"]);
- const delay = countdown ? 3500 : 500;
+ const delay = countdown ? 3120 : 300;
setTimeout(() => {
if (countdown) {
diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsx
index 6d0c847..7c561d0 100644
--- a/src/pages/CloudRecorder/CloudRecorder.jsx
+++ b/src/pages/CloudRecorder/CloudRecorder.jsx
@@ -1,6 +1,6 @@
import React, { useEffect, useState, useRef, useCallback } from "react";
import RecorderUI from "./RecorderUI";
-import { sendRecordingError, sendStopRecording } from "./messaging";
+import { sendRecordingError as sendRecordingErrorBase, sendStopRecording } from "./messaging";
import { getBitrates, getResolutionForQuality } from "./recorderConfig";
import BunnyTusUploader from "./bunnyTusUploader";
import localforage from "localforage";
@@ -47,6 +47,7 @@ const CloudRecorder = () => {
const screenUploader = useRef(null);
const cameraUploader = useRef(null);
const uploadMetaRef = useRef(null);
+ const emptyCleanupRef = useRef(false);
const backupRef = useRef(false);
const audioInputGain = useRef(null);
@@ -632,8 +633,65 @@ const CloudRecorder = () => {
});
};
+ const cleanupIfEmptyUploads = async (reason) => {
+ if (emptyCleanupRef.current) return;
+ const screenOffset = screenUploader.current?.offset ?? null;
+ const cameraOffset = cameraUploader.current?.offset ?? null;
+ const hasScreen = screenOffset !== null;
+ const hasCamera = cameraOffset !== null;
+
+ if (!hasScreen && !hasCamera) return;
+
+ const isEmpty =
+ (!hasScreen || screenOffset === 0) && (!hasCamera || cameraOffset === 0);
+
+ if (!isEmpty) return;
+
+ emptyCleanupRef.current = true;
+
+ console.warn("[Screenity] empty upload cleanup", {
+ reason,
+ screenOffset,
+ cameraOffset,
+ });
+
+ await Promise.allSettled([
+ screenUploader.current?.abort?.(),
+ cameraUploader.current?.abort?.(),
+ ]);
+
+ try {
+ const { projectId, recordingToScene } = await chrome.storage.local.get([
+ "projectId",
+ "recordingToScene",
+ ]);
+ const uploadMeta =
+ uploadMetaRef.current || {
+ screen: screenUploader.current?.getMeta?.() || null,
+ camera: cameraUploader.current?.getMeta?.() || null,
+ audio: null,
+ sceneId:
+ screenUploader.current?.getMeta?.()?.sceneId ||
+ cameraUploader.current?.getMeta?.()?.sceneId ||
+ null,
+ };
+
+ if (projectId && uploadMeta) {
+ await deleteProject(projectId, uploadMeta, !recordingToScene);
+ }
+ } catch (err) {
+ console.warn("❌ Failed to cleanup empty upload:", err);
+ }
+ };
+
+ const sendRecordingError = (why, cancel = false) => {
+ void cleanupIfEmptyUploads("error");
+ sendRecordingErrorBase(why, cancel);
+ };
+
const dismissRecording = async (restarting = false) => {
setInitProject(false);
+ await cleanupIfEmptyUploads(restarting ? "restart" : "dismiss");
// Stop the silent audio keep-alive
stopTabKeepAlive();
@@ -784,6 +842,7 @@ const CloudRecorder = () => {
const initializeUploaders = async () => {
try {
+ emptyCleanupRef.current = false;
const { projectId } = await chrome.storage.local.get(["projectId"]);
const sceneId = crypto.randomUUID();
@@ -1763,6 +1822,7 @@ const CloudRecorder = () => {
{ screenStatus, cameraStatus, screenOffset, cameraOffset }
);
} else {
+ await cleanupIfEmptyUploads("no-upload");
await exportLocalRecovery("no-upload");
await finalizeRecorderSession("failed");
sendRecordingError(
@@ -1796,8 +1856,9 @@ const CloudRecorder = () => {
await chunksStore.clear().catch(() => {});
if (!IS_IFRAME_CONTEXT) {
- // FLAG: decide whether to close or not
- //window.close();
+ try {
+ window.close();
+ } catch {}
} else {
window.location.reload();
}
@@ -1835,8 +1896,9 @@ const CloudRecorder = () => {
// Give user time to see the error message
setTimeout(() => {
if (!IS_IFRAME_CONTEXT) {
- // FLAG: decide whether to close or not
- //window.close();
+ try {
+ window.close();
+ } catch {}
} else {
window.location.reload();
}
@@ -2431,9 +2493,9 @@ const CloudRecorder = () => {
if (!isInit.current) return;
if (IS_IFRAME_CONTEXT) {
- if (request.region) setTimeout(() => startRecording(), 100);
+ if (request.region) setTimeout(() => startRecording(), 10);
} else if (!regionRef.current) {
- setTimeout(() => startRecording(), 100);
+ setTimeout(() => startRecording(), 10);
}
} else if (request.type === "restart-recording-tab") {
if (!isInit.current) return;
diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsx
index 06b2c85..47bd0b0 100644
--- a/src/pages/Content/context/ContentState.jsx
+++ b/src/pages/Content/context/ContentState.jsx
@@ -1,4 +1,10 @@
-import React, { createContext, useState, useEffect, useCallback } from "react";
+import React, {
+ createContext,
+ useState,
+ useEffect,
+ useCallback,
+ useRef,
+} from "react";
import { updateFromStorage } from "./utils/updateFromStorage";
@@ -41,6 +47,29 @@ const ContentState = (props) => {
const [URL2, setURL2] = useState(
"https://help.screenity.io/troubleshooting/9Jy5RGjNrBB42hqUdREQ7W/how-to-grant-screenity-permission-to-record-your-camera-and-microphone/x6U69TnrbMjy5CQ96Er2E9"
);
+ const startBeepRef = useRef(null);
+ const stopBeepRef = useRef(null);
+ const prevRecordingRef = useRef(null);
+ const hydratedRef = useRef(false);
+ const suppressStopBeepRef = useRef(false);
+ const suppressStartBeepRef = useRef(false);
+ const tabIdRef = useRef(null);
+ const activeTabRef = useRef(null);
+ const tabRecordedIdRef = useRef(null);
+
+ const isTargetTab = useCallback(() => {
+ const tabId = tabIdRef.current;
+ const tabRecordedID = tabRecordedIdRef.current;
+ const activeTab = activeTabRef.current;
+
+ if (tabRecordedID != null) {
+ return tabId != null && tabId === tabRecordedID;
+ }
+ if (activeTab != null) {
+ return tabId != null && tabId === activeTab;
+ }
+ return true;
+ }, []);
// Check if the user is logged in
const verifyUser = async () => {
@@ -74,6 +103,19 @@ const ContentState = (props) => {
verifyUser();
}, []);
+ useEffect(() => {
+ chrome.runtime.sendMessage({ type: "get-tab-id" }, (response) => {
+ if (response?.tabId !== undefined && response?.tabId !== null) {
+ tabIdRef.current = response.tabId;
+ }
+ });
+
+ chrome.storage.local.get(["activeTab", "tabRecordedID"], (result) => {
+ activeTabRef.current = result.activeTab ?? null;
+ tabRecordedIdRef.current = result.tabRecordedID ?? null;
+ });
+ }, []);
+
useEffect(() => {
const locale = chrome.i18n.getMessage("@@ui_locale");
if (!locale.includes("en")) {
@@ -91,6 +133,9 @@ const ContentState = (props) => {
}, []);
const startRecording = useCallback(() => {
+ const shouldClearCountdown =
+ !contentStateRef.current?.isCountdownVisible &&
+ !contentStateRef.current?.countdownActive;
if (contentStateRef.current.alarm) {
if (contentStateRef.current.alarmTime === 0) {
setContentState((prevContentState) => ({
@@ -112,6 +157,9 @@ const ContentState = (props) => {
timeWarning: false,
pendingRecording: false,
preparingRecording: false,
+ ...(shouldClearCountdown
+ ? { countdownActive: false, isCountdownVisible: false }
+ : {}),
}));
chrome.storage.local.set({ restarting: false });
@@ -203,10 +251,6 @@ const ContentState = (props) => {
}, 200);
}
});
- // Play beep sound at 50% volume
- const audio = new Audio(chrome.runtime.getURL("/assets/sounds/beep.mp3"));
- audio.volume = 0.5;
- audio.play();
});
const pauseRecording = useCallback((dismiss) => {
@@ -238,6 +282,7 @@ const ContentState = (props) => {
});
const dismissRecording = useCallback(() => {
+ suppressStopBeepRef.current = true;
chrome.storage.local.set({ restarting: false });
chrome.runtime.sendMessage({ type: "dismiss-recording-tab" });
setContentState((prevContentState) => ({
@@ -640,9 +685,11 @@ const ContentState = (props) => {
chrome.storage.local.set({
defaultAudioInputLabel:
- defaultAudioInputLabel || contentStateRef.current.defaultAudioInputLabel,
+ defaultAudioInputLabel ||
+ contentStateRef.current.defaultAudioInputLabel,
defaultVideoInputLabel:
- defaultVideoInputLabel || contentStateRef.current.defaultVideoInputLabel,
+ defaultVideoInputLabel ||
+ contentStateRef.current.defaultVideoInputLabel,
});
chrome.runtime.sendMessage({
@@ -874,12 +921,9 @@ const ContentState = (props) => {
showProSplash: false,
hasSubscribedBefore: false,
startRecordingAfterCountdown: () => {
- playBeepSound();
- setTimeout(() => {
- if (!contentStateRef.current.countdownCancelled) {
- contentStateRef.current.startRecording();
- }
- }, 500);
+ if (!contentStateRef.current.countdownCancelled) {
+ contentStateRef.current.startRecording();
+ }
},
cancelCountdown: () => {
setContentState((prev) => ({
@@ -900,6 +944,12 @@ const ContentState = (props) => {
countdownCancelled: false,
}));
},
+ onCountdownFinished: () => {
+ if (!contentStateRef.current?.countdownCancelled && isTargetTab()) {
+ suppressStartBeepRef.current = true;
+ playBeep(startBeepRef, "assets/sounds/beep2.mp3");
+ }
+ },
});
contentStateRef.current = contentState;
@@ -916,19 +966,66 @@ const ContentState = (props) => {
}
};
- const playBeepSound = () => {
- const audio = new Audio(chrome.runtime.getURL("/assets/sounds/beep2.mp3"));
+ const playBeep = (ref, filename) => {
+ if (!ref.current) {
+ ref.current = new Audio(chrome.runtime.getURL(filename));
+ }
+ const audio = ref.current;
audio.volume = 0.5;
- audio.play();
+ try {
+ audio.currentTime = 0;
+ } catch {}
+ const playPromise = audio.play();
+ if (playPromise?.catch) {
+ playPromise.catch((error) => {
+ console.warn("Beep playback failed:", error);
+ });
+ }
};
useEffect(() => {
chrome.runtime.sendMessage({ type: "sync-recording-state" }, (state) => {
if (!state) return;
setContentState((prev) => ({ ...prev, ...state }));
+ setTimeout(() => {
+ hydratedRef.current = true;
+ prevRecordingRef.current = Boolean(state.recording);
+ }, 0);
});
}, []);
+ useEffect(() => {
+ const isRecording = Boolean(contentState.recording);
+ if (!hydratedRef.current) {
+ prevRecordingRef.current = isRecording;
+ return;
+ }
+ if (prevRecordingRef.current === null) {
+ prevRecordingRef.current = isRecording;
+ return;
+ }
+ if (!isTargetTab()) {
+ prevRecordingRef.current = isRecording;
+ return;
+ }
+
+ if (prevRecordingRef.current === false && isRecording === true) {
+ if (suppressStartBeepRef.current) {
+ suppressStartBeepRef.current = false;
+ } else {
+ playBeep(startBeepRef, "assets/sounds/beep2.mp3");
+ }
+ } else if (prevRecordingRef.current === true && isRecording === false) {
+ if (suppressStopBeepRef.current) {
+ suppressStopBeepRef.current = false;
+ } else {
+ playBeep(stopBeepRef, "assets/sounds/beep.mp3");
+ }
+ }
+
+ prevRecordingRef.current = isRecording;
+ }, [contentState.recording, isTargetTab]);
+
useEffect(() => {
if (!CLOUD_FEATURES_ENABLED) return;
if (!contentState.isLoggedIn || !contentState.isSubscribed) return;
@@ -1030,19 +1127,14 @@ const ContentState = (props) => {
}, [contentState.openModal]);
const updateTimerFromStorage = useCallback(async () => {
- const {
- recording,
- recordingStartTime,
- paused,
- pausedAt,
- totalPausedMs,
- } = await chrome.storage.local.get([
- "recording",
- "recordingStartTime",
- "paused",
- "pausedAt",
- "totalPausedMs",
- ]);
+ const { recording, recordingStartTime, paused, pausedAt, totalPausedMs } =
+ await chrome.storage.local.get([
+ "recording",
+ "recordingStartTime",
+ "paused",
+ "pausedAt",
+ "totalPausedMs",
+ ]);
if (!recording || !recordingStartTime) {
setTimer(0);
@@ -1051,8 +1143,7 @@ const ContentState = (props) => {
const now = Date.now();
const basePaused = totalPausedMs || 0;
- const extraPaused =
- paused && pausedAt ? Math.max(0, now - pausedAt) : 0;
+ const extraPaused = paused && pausedAt ? Math.max(0, now - pausedAt) : 0;
const elapsedSeconds = Math.max(
0,
Math.floor((now - recordingStartTime - basePaused - extraPaused) / 1000)
@@ -1064,7 +1155,22 @@ const ContentState = (props) => {
return;
}
- setTimer(elapsedSeconds);
+ setTimer((prev) => {
+ if (!Number.isFinite(prev)) {
+ return elapsedSeconds;
+ }
+ if (elapsedSeconds <= prev) {
+ return elapsedSeconds;
+ }
+ const delta = elapsedSeconds - prev;
+ if (delta <= 1) {
+ return elapsedSeconds;
+ }
+ if (delta <= 3) {
+ return prev + 1;
+ }
+ return elapsedSeconds;
+ });
}, []);
useEffect(() => {
@@ -1079,6 +1185,12 @@ const ContentState = (props) => {
const onChanged = (changes, area) => {
if (area !== "local") return;
+ if (changes.activeTab) {
+ activeTabRef.current = changes.activeTab.newValue ?? null;
+ }
+ if (changes.tabRecordedID) {
+ tabRecordedIdRef.current = changes.tabRecordedID.newValue ?? null;
+ }
if (changes.paused) {
setContentState((prev) => ({
...prev,
@@ -1086,9 +1198,27 @@ const ContentState = (props) => {
}));
}
if (changes.recording) {
+ const isRecording = Boolean(changes.recording.newValue);
+ if (isRecording && !isTargetTab()) {
+ setContentState((prev) => ({
+ ...prev,
+ recording: false,
+ }));
+ return;
+ }
+ const shouldHideCountdown =
+ isRecording &&
+ !contentStateRef.current?.isCountdownVisible &&
+ !contentStateRef.current?.countdownActive;
setContentState((prev) => ({
...prev,
- recording: Boolean(changes.recording.newValue),
+ recording: isRecording,
+ ...(shouldHideCountdown
+ ? {
+ countdownActive: false,
+ isCountdownVisible: false,
+ }
+ : {}),
}));
}
if (changes.cursorEffects) {
@@ -1130,7 +1260,7 @@ const ContentState = (props) => {
chrome.storage.onChanged.addListener(onChanged);
return () => chrome.storage.onChanged.removeListener(onChanged);
- }, [updateTimerFromStorage]);
+ }, [isTargetTab, updateTimerFromStorage]);
useEffect(() => {
if (!contentState.customRegion) {
@@ -1171,7 +1301,6 @@ const ContentState = (props) => {
}
}, []);
-
useEffect(() => {
if (contentState.pushToTalk) {
setContentState((prevContentState) => ({
diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.js
index 7586d56..3ddb824 100644
--- a/src/pages/Content/context/messaging/handlers.js
+++ b/src/pages/Content/context/messaging/handlers.js
@@ -5,7 +5,6 @@ import {
} from "../../../../messaging/messageRouter";
import { setContentState, contentStateRef } from "../ContentState";
import { updateFromStorage } from "../utils/updateFromStorage";
-import { setTimer } from "../ContentState";
import { checkAuthStatus } from "../utils/checkAuthStatus";
@@ -15,6 +14,8 @@ const CLOUD_FEATURES_ENABLED =
const getState = () => contentStateRef.current;
export const setupHandlers = () => {
+ let lastToggleDrawingAt = 0;
+ const TOGGLE_DRAWING_COOLDOWN_MS = 400;
// Initialize message router
if (!window.__screenityHandlersInitialized) {
messageRouter();
@@ -22,12 +23,9 @@ export const setupHandlers = () => {
}
// Register content message handlers
- registerMessage("time", (message) => {
- chrome.storage.local.get(["recording"], (result) => {
- if (result.recording) {
- setTimer(message.time);
- }
- });
+ registerMessage("time", () => {
+ // Timer is driven by ContentState's storage-based tick.
+ // Ignore external timer pushes to avoid jitter/skips.
});
registerMessage("toggle-popup", () => {
@@ -75,16 +73,20 @@ export const setupHandlers = () => {
});
registerMessage("toggle-drawing-mode", () => {
+ const now = Date.now();
+ if (now - lastToggleDrawingAt < TOGGLE_DRAWING_COOLDOWN_MS) {
+ return;
+ }
+ lastToggleDrawingAt = now;
+ if (document.hidden || !document.hasFocus()) {
+ return;
+ }
const nextDrawingMode = !contentStateRef.current.drawingMode;
setContentState((prev) => ({
...prev,
drawingMode: nextDrawingMode,
blurMode: nextDrawingMode ? false : prev.blurMode,
}));
- chrome.storage.local.set({
- drawingMode: nextDrawingMode,
- blurMode: nextDrawingMode ? false : contentStateRef.current.blurMode,
- });
});
registerMessage("toggle-blur-mode", () => {
@@ -330,13 +332,6 @@ export const setupHandlers = () => {
});
registerMessage("recording-check", (message, sender) => {
- const { recordingStartTime } = message;
-
- if (recordingStartTime) {
- const time = Math.floor((Date.now() - recordingStartTime) / 1000);
- setTimer(time);
- }
-
const state = getState();
if (!message.force) {
diff --git a/src/pages/Content/context/utils/updateFromStorage.js b/src/pages/Content/context/utils/updateFromStorage.js
index 1def1b0..2eb4250 100644
--- a/src/pages/Content/context/utils/updateFromStorage.js
+++ b/src/pages/Content/context/utils/updateFromStorage.js
@@ -68,9 +68,6 @@ export const updateFromStorage = (check = true, id = null) => {
"backupSetup",
"qualityValue",
"fpsValue",
- "countdownActive",
- "countdownCancelled",
- "isCountdownVisible",
"multiMode",
"multiSceneCount",
"sortBy",
@@ -303,9 +300,6 @@ export const updateFromStorage = (check = true, id = null) => {
result.fpsValue !== undefined && result.fpsValue !== null
? result.fpsValue
: prevContentState.fpsValue,
- countdownActive: result.countdownActive || false,
- countdownCancelled: result.countdownCancelled || false,
- isCountdownVisible: result.isCountdownVisible || false,
multiMode: result.multiMode || false,
multiSceneCount: result.multiSceneCount || 0,
wasLoggedIn: result.wasLoggedIn || false,
diff --git a/src/pages/Content/countdown/Countdown.jsx b/src/pages/Content/countdown/Countdown.jsx
index 9471e04..2dbc60f 100644
--- a/src/pages/Content/countdown/Countdown.jsx
+++ b/src/pages/Content/countdown/Countdown.jsx
@@ -11,23 +11,58 @@ const Countdown = () => {
const [isTransforming, setIsTransforming] = useState(false);
const [isRotating, setIsRotating] = useState(false);
- const timers = useRef([]);
+ const END_HOLD_MS = 1000;
+ const START_AFTER_BEEP_MS = 120;
+ const HIDE_AFTER_END_MS = 0;
+
+ const intervalRef = useRef(null);
+ const activeRef = useRef(false);
+ const cancelledRef = useRef(false);
+ const wasVisibleRef = useRef(false);
+ const startRef = useRef(null);
+ const finishRef = useRef(null);
+ const resetRef = useRef(null);
+ const completedRef = useRef(false);
+ const hideTimeoutRef = useRef(null);
+ const finishTimeoutRef = useRef(null);
+ const startTimeoutRef = useRef(null);
- // Cleanup function to clear all timers
const cleanupTimers = () => {
- timers.current.forEach((timer) => {
- if (timer.type === "interval") {
- clearInterval(timer.id);
- } else {
- clearTimeout(timer.id);
- }
- });
- timers.current = [];
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+ if (hideTimeoutRef.current) {
+ clearTimeout(hideTimeoutRef.current);
+ hideTimeoutRef.current = null;
+ }
+ if (finishTimeoutRef.current) {
+ clearTimeout(finishTimeoutRef.current);
+ finishTimeoutRef.current = null;
+ }
+ if (startTimeoutRef.current) {
+ clearTimeout(startTimeoutRef.current);
+ startTimeoutRef.current = null;
+ }
};
+ useEffect(() => {
+ activeRef.current = contentState.countdownActive;
+ cancelledRef.current = contentState.countdownCancelled;
+ startRef.current = contentState.startRecordingAfterCountdown;
+ finishRef.current = contentState.onCountdownFinished;
+ resetRef.current = contentState.resetCountdown;
+ }, [
+ contentState.countdownActive,
+ contentState.countdownCancelled,
+ contentState.startRecordingAfterCountdown,
+ contentState.onCountdownFinished,
+ contentState.resetCountdown,
+ ]);
+
// Handle cancellation
const handleCancel = () => {
- if (contentState.countdownActive) {
+ if (contentState.countdownActive || contentState.isCountdownVisible) {
cleanupTimers();
setCount(COUNTDOWN_TIME);
setIsTransforming(false);
@@ -38,72 +73,94 @@ const Countdown = () => {
// Countdown logic
useEffect(() => {
- if (contentState.countdownActive && count > 1) {
- const intervalId = setInterval(() => {
- if (!contentState.countdownCancelled) {
- setCount((prev) => prev - 1);
- }
- }, 1000);
+ if (!contentState.countdownActive) {
+ cleanupTimers();
+ return;
+ }
- timers.current.push({ id: intervalId, type: "interval" });
+ cleanupTimers();
+ intervalRef.current = setInterval(() => {
+ setCount((prev) => (prev > 1 ? prev - 1 : 1));
+ }, 1000);
- return () => {
- clearInterval(intervalId);
- timers.current = timers.current.filter((t) => t.id !== intervalId);
- };
- } else if (contentState.countdownActive && count === 1) {
- const timeoutId = setTimeout(() => {
- if (!contentState.countdownCancelled && contentState.countdownActive) {
- contentState.startRecordingAfterCountdown();
+ return cleanupTimers;
+ }, [contentState.countdownActive]);
+
+ useEffect(() => {
+ if (!activeRef.current || cancelledRef.current) {
+ return;
+ }
+ if (count !== 1) {
+ return;
+ }
+ if (completedRef.current) {
+ return;
+ }
+ completedRef.current = true;
+
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+
+ if (!cancelledRef.current && activeRef.current) {
+ finishTimeoutRef.current = setTimeout(() => {
+ if (cancelledRef.current || !activeRef.current) {
+ finishTimeoutRef.current = null;
+ return;
+ }
+ finishRef.current?.();
+ startTimeoutRef.current = setTimeout(() => {
+ startRef.current?.();
+ startTimeoutRef.current = null;
+ }, START_AFTER_BEEP_MS);
+ hideTimeoutRef.current = setTimeout(() => {
setContentState((prev) => ({
...prev,
isCountdownVisible: false,
countdownActive: false,
}));
- }
- }, 1000);
-
- timers.current.push({ id: timeoutId, type: "timeout" });
-
- return () => {
- clearTimeout(timeoutId);
- timers.current = timers.current.filter((t) => t.id !== timeoutId);
- };
+ hideTimeoutRef.current = null;
+ }, HIDE_AFTER_END_MS);
+ finishTimeoutRef.current = null;
+ }, END_HOLD_MS);
}
- }, [contentState.countdownActive, count, setContentState, contentState]);
+ }, [count, setContentState]);
// Start animation when countdown becomes visible
useEffect(() => {
- if (contentState.isCountdownVisible) {
- contentState.resetCountdown(); // Reset cancelled state
+ if (contentState.isCountdownVisible && !wasVisibleRef.current) {
+ resetRef.current?.();
+ completedRef.current = false;
setCount(COUNTDOWN_TIME);
setIsTransforming(true);
const rotateId = setTimeout(() => {
- if (!contentState.countdownCancelled) {
+ if (!cancelledRef.current) {
setIsRotating(true);
}
}, 10);
const transformId = setTimeout(() => {
- if (!contentState.countdownCancelled) {
+ if (!cancelledRef.current) {
setIsTransforming(false);
}
}, (COUNTDOWN_TIME * 1000) / 2);
- timers.current.push(
- { id: rotateId, type: "timeout" },
- { id: transformId, type: "timeout" }
- );
-
return () => {
clearTimeout(rotateId);
clearTimeout(transformId);
- timers.current = timers.current.filter(
- (t) => t.id !== rotateId && t.id !== transformId
- );
};
}
+
+ if (!contentState.isCountdownVisible) {
+ setIsRotating(false);
+ setIsTransforming(false);
+ }
+ }, [contentState.isCountdownVisible]);
+
+ useEffect(() => {
+ wasVisibleRef.current = contentState.isCountdownVisible;
}, [contentState.isCountdownVisible]);
// Cleanup on unmount
diff --git a/src/pages/Content/shortcuts/Shortcuts.jsx b/src/pages/Content/shortcuts/Shortcuts.jsx
index 737b2df..78320b7 100644
--- a/src/pages/Content/shortcuts/Shortcuts.jsx
+++ b/src/pages/Content/shortcuts/Shortcuts.jsx
@@ -34,10 +34,7 @@ const Shortcuts = ({ shortcuts }) => {
});
*/
- // In-app shortcuts (number keys) for Screenity tools.
- // 1: select, 2: pen, 3: highlighter, 4: eraser, 5: color picker
- // 6: text, 7: shape (rectangle), 8: arrow, 9: image, 0: clear
- // Cursor effects: 0 clears, 1 target, 2 highlight, 3 spotlight
+ // in-app shortcuts for screenity tools
useEffect(() => {
const getDeepActiveElement = () => {
let active = document.activeElement;
@@ -126,8 +123,8 @@ const Shortcuts = ({ shortcuts }) => {
const openImagePicker = () => {
const shadowRoot = getShadowRoot();
const fileInput = shadowRoot
- ? shadowRoot.querySelector("[data-image-upload=\"true\"]")
- : document.querySelector("[data-image-upload=\"true\"]");
+ ? shadowRoot.querySelector('[data-image-upload="true"]')
+ : document.querySelector('[data-image-upload="true"]');
if (fileInput) {
fileInput.click();
}
@@ -183,10 +180,7 @@ const Shortcuts = ({ shortcuts }) => {
undoCanvas(state, setContentState);
return;
}
- if (
- (key === "z" && event.shiftKey) ||
- key === "y"
- ) {
+ if ((key === "z" && event.shiftKey) || key === "y") {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsx
index 025cccf..af0ce42 100644
--- a/src/pages/Sandbox/context/ContentState.jsx
+++ b/src/pages/Sandbox/context/ContentState.jsx
@@ -11,6 +11,11 @@ import fixWebmDuration from "fix-webm-duration";
import { default as fixWebmDurationFallback } from "webm-duration-fix";
import localforage from "localforage";
+import {
+ formatLocalTimestamp,
+ getHostnameFromUrl,
+ sanitizeFilenameBase,
+} from "../../utils/filenameHelpers";
localforage.config({
driver: localforage.INDEXEDDB,
@@ -88,6 +93,7 @@ const ContentState = (props) => {
chunkIndex: 0,
bannerSupport: false,
backupBlob: null,
+ recordingMeta: null,
};
const [contentState, setContentState] = useState(defaultState);
@@ -127,21 +133,51 @@ const ContentState = (props) => {
// }
// }, []);
- // Generate a title based on the current time (e.g. Screenity video - Sep 4 2021 10:00 AM)
+ // Generate a title based on the current time unless this is a tab recording
useEffect(() => {
- const date = new Date();
- const formattedDate = date.toLocaleString("en-US", {
- month: "short",
- day: "numeric",
- year: "numeric",
- hour: "numeric",
- minute: "2-digit",
- hour12: true,
- });
- setContentState((prevState) => ({
- ...prevState,
- title: `Screenity video - ${formattedDate}`,
- }));
+ const loadInitialTitle = async () => {
+ const date = new Date();
+ const formattedDate = date.toLocaleString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ hour12: true,
+ });
+ const fallbackTitle = `Screenity video - ${formattedDate}`;
+
+ try {
+ const { recordingMeta } = await chrome.storage.local.get([
+ "recordingMeta",
+ ]);
+ if (recordingMeta?.type === "tab") {
+ const baseTitle = sanitizeFilenameBase(
+ recordingMeta.title?.trim() ||
+ getHostnameFromUrl(recordingMeta.url) ||
+ fallbackTitle
+ );
+ const timestamp = formatLocalTimestamp(recordingMeta.startedAt);
+ setContentState((prevState) => ({
+ ...prevState,
+ title: `${baseTitle} β€” ${timestamp}`,
+ recordingMeta,
+ }));
+ chrome.storage.local.remove(["recordingMeta"]);
+ return;
+ }
+ } catch (error) {
+ console.warn("Failed to load recording meta:", error);
+ }
+
+ setContentState((prevState) => ({
+ ...prevState,
+ title: fallbackTitle,
+ recordingMeta: null,
+ }));
+ };
+
+ loadInitialTitle();
}, []);
// Show a popup when attempting to close the tab if the user has not downloaded their video
@@ -1063,8 +1099,31 @@ const ContentState = (props) => {
};
const requestDownload = async (url, ext) => {
- const title =
- contentStateRef.current.title.replace(/[\/\\:?~<>|*]/g, " ").trim() + ext;
+ let recordingMeta = contentStateRef.current.recordingMeta;
+ if (!recordingMeta) {
+ try {
+ const stored = await chrome.storage.local.get(["recordingMeta"]);
+ if (stored.recordingMeta?.type === "tab") {
+ recordingMeta = stored.recordingMeta;
+ chrome.storage.local.remove(["recordingMeta"]);
+ }
+ } catch (error) {
+ console.warn("Failed to load recording meta for download:", error);
+ }
+ }
+ const currentTitle = contentStateRef.current.title || "";
+ const safeTitle = currentTitle || "Screenity recording";
+ let title = safeTitle.replace(/[\/\\:?~<>|*]/g, " ").trim() + ext;
+
+ if (recordingMeta?.type === "tab") {
+ const baseTitle = sanitizeFilenameBase(
+ currentTitle && currentTitle.trim().length > 0
+ ? currentTitle
+ : recordingMeta.title || getHostnameFromUrl(recordingMeta.url)
+ );
+ const timestamp = formatLocalTimestamp(recordingMeta.startedAt);
+ title = `${baseTitle} β€” ${timestamp}${ext}`;
+ }
const revoke = () => {
try {
diff --git a/src/pages/utils/filenameHelpers.js b/src/pages/utils/filenameHelpers.js
new file mode 100644
index 0000000..935b74c
--- /dev/null
+++ b/src/pages/utils/filenameHelpers.js
@@ -0,0 +1,45 @@
+export const sanitizeFilenameBase = (value) => {
+ const fallback = "Screenity recording";
+ if (typeof value !== "string") return fallback;
+
+ let sanitized = value.replace(/[\u0000-\u001f\u007f]/g, "");
+ sanitized = sanitized.replace(/[\\/:*?"<>|]/g, "-");
+ sanitized = sanitized.replace(/\s+/g, " ").trim();
+
+ if (sanitized.length > 80) {
+ sanitized = sanitized.slice(0, 80).trim();
+ }
+
+ return sanitized.length > 0 ? sanitized : fallback;
+};
+
+export const formatLocalTimestamp = (value) => {
+ const date = value ? new Date(value) : new Date();
+ const safeDate = Number.isNaN(date.getTime()) ? new Date() : date;
+ // Use Intl.DateTimeFormat to respect user locale and time format.
+ return new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ }).format(safeDate);
+};
+
+export const getHostnameFromUrl = (url) => {
+ if (!url) return "";
+ try {
+ const parsed = new URL(url);
+ let hostname = parsed.hostname || "";
+ if (hostname.startsWith("www.")) {
+ hostname = hostname.slice(4);
+ }
+ return hostname;
+ } catch {
+ return "";
+ }
+};
+
+export const getTabRecordingBaseTitle = (title, url) => {
+ const candidate = title && title.trim().length > 0 ? title : getHostnameFromUrl(url);
+ return sanitizeFilenameBase(candidate);
+};
diff --git a/src/pages/utils/mediaDeviceFallback.js b/src/pages/utils/mediaDeviceFallback.js
new file mode 100644
index 0000000..03ce4f8
--- /dev/null
+++ b/src/pages/utils/mediaDeviceFallback.js
@@ -0,0 +1,87 @@
+const DEVICE_ID_ERRORS = new Set(["OverconstrainedError", "NotFoundError"]);
+
+const isDeviceIdError = (err) => err && DEVICE_ID_ERRORS.has(err.name);
+
+const cloneConstraints = (constraints) =>
+ JSON.parse(JSON.stringify(constraints || {}));
+
+const updateConstraintsDeviceId = (constraints, kind, deviceId) => {
+ if (!constraints || !deviceId) return;
+
+ if (kind === "audioinput") {
+ if (!constraints.audio || typeof constraints.audio !== "object") return;
+ constraints.audio = {
+ ...constraints.audio,
+ deviceId: { exact: deviceId },
+ };
+ return;
+ }
+
+ if (kind === "videoinput") {
+ if (!constraints.video || typeof constraints.video !== "object") return;
+ constraints.video = {
+ ...constraints.video,
+ deviceId: { exact: deviceId },
+ };
+ }
+};
+
+export const enumerateCurrentDevices = async () => {
+ try {
+ return await navigator.mediaDevices.enumerateDevices();
+ } catch (err) {
+ console.warn("Failed to enumerate devices:", err);
+ return [];
+ }
+};
+
+export const resolveDeviceIdByLabel = async (kind, desiredLabel) => {
+ if (!desiredLabel) return null;
+ const devices = await enumerateCurrentDevices();
+ const matches = devices.filter(
+ (device) => device.kind === kind && device.label === desiredLabel
+ );
+ if (matches.length !== 1) return null;
+ return matches[0].deviceId;
+};
+
+export const getUserMediaWithFallback = async ({
+ constraints,
+ fallbacks = [],
+}) => {
+ try {
+ return await navigator.mediaDevices.getUserMedia(constraints);
+ } catch (err) {
+ if (!isDeviceIdError(err) || fallbacks.length === 0) {
+ throw err;
+ }
+
+ const nextConstraints = cloneConstraints(constraints);
+ const resolved = [];
+
+ for (const fallback of fallbacks) {
+ const { kind, desiredLabel, desiredDeviceId } = fallback || {};
+ if (!kind || !desiredLabel || !desiredDeviceId) continue;
+ const resolvedId = await resolveDeviceIdByLabel(kind, desiredLabel);
+ if (!resolvedId || resolvedId === desiredDeviceId) continue;
+ updateConstraintsDeviceId(nextConstraints, kind, resolvedId);
+ resolved.push({ ...fallback, resolvedId });
+ }
+
+ if (resolved.length === 0) {
+ throw err;
+ }
+
+ console.warn(
+ "[Screenity] Retrying getUserMedia with label-matched device IDs"
+ );
+
+ const stream = await navigator.mediaDevices.getUserMedia(nextConstraints);
+ resolved.forEach(({ resolvedId, onResolved }) => {
+ if (typeof onResolved === "function") {
+ onResolved(resolvedId);
+ }
+ });
+ return stream;
+ }
+};
diff --git a/webpack.config.js b/webpack.config.js
index c82d58a..d787e7b 100755
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -30,6 +30,13 @@ const entryPoints = {
"RecorderOffscreen",
"index.jsx"
),
+ audiooffscreen: path.join(
+ __dirname,
+ "src",
+ "pages",
+ "AudioOffscreen",
+ "index.js"
+ ),
camera: path.join(__dirname, "src", "pages", "Camera", "index.jsx"),
waveform: path.join(__dirname, "src", "pages", "Waveform", "index.jsx"),
sandbox: path.join(__dirname, "src", "pages", "Sandbox", "index.jsx"),
@@ -67,6 +74,7 @@ const htmlPlugins = Object.keys(entryPoints)
const folderNameMap = {
cloudrecorder: "CloudRecorder",
recorderoffscreen: "RecorderOffscreen",
+ audiooffscreen: "AudioOffscreen",
editorwebcodecs: "EditorWebCodecs",
editorviewer: "EditorViewer",
};