Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#6649: Exclude navigation events that should not trigger page updates #7178

Merged
merged 8 commits into from
Dec 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const config = {
"^.+\\.txt$": "<rootDir>/src/testUtils/rawJestTransformer.mjs",
},
transformIgnorePatterns: [
"node_modules/(?!@cfworker|escape-string-regex|filename-reserved-regex|filenamify|idb|webext-|p-timeout|p-retry|p-defer|p-memoize|serialize-error|strip-outer|trim-repeated|mimic-fn|urlpattern-polyfill|url-join|uuid|nanoid|use-debounce|copy-text-to-clipboard|linkify-urls|create-html-element|stringify-attributes|escape-goat|stemmer|uint8array-extras)",
"node_modules/(?!@cfworker|escape-string-regex|filename-reserved-regex|filenamify|idb|webext-|p-timeout|p-retry|p-defer|p-memoize|serialize-error|strip-outer|trim-repeated|mimic-fn|urlpattern-polyfill|url-join|uuid|nanoid|use-debounce|copy-text-to-clipboard|linkify-urls|create-html-element|stringify-attributes|escape-goat|stemmer|uint8array-extras|one-event)",
],
setupFiles: [
"dotenv/config",
Expand Down
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
"mustache": "^4.2.0",
"nunjucks": "^3.2.4",
"object-hash": "^2.2.0",
"one-event": "^4.2.0",
"one-mutation": "^2.1.0",
"p-defer": "^4.0.0",
"p-memoize": "^7.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ registerMessenger();
registerExternalMessenger();
initBrowserAction();
initInstaller();
initNavigation();
void initNavigation();
initExecutor();
initContextMenus();
initContentScriptReadyListener();
Expand Down
31 changes: 15 additions & 16 deletions src/background/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import { type Target } from "@/types/messengerTypes";
import { canAccessTab } from "@/permissions/permissionsUtils";
import { isScriptableUrl } from "webext-content-scripts";
import { debounce } from "lodash";
import { syncFlagOn } from "@/store/syncFlags";
import { canAccessTab as canInjectTab, getTabUrl } from "webext-tools";
import { getTargetState } from "@/contentScript/ready";
import { flagOn } from "@/auth/authUtils";

export function reactivateEveryTab(): void {
console.debug("Reactivate all tabs");
Expand All @@ -40,33 +40,32 @@ async function traceNavigation(target: Target): Promise<void> {
...target,
tabUrl,
isScriptableUrl: isScriptableUrl(tabUrl),
contentScriptState: await getTargetState(target),
canInject: await canInjectTab(target),
// PixieBrix has some additional constraints on which tabs can be accessed (i.e., only https:)
canAccessTab: await canAccessTab(target),
contentScriptState: getTargetState(target),
canInject: canInjectTab(target),
// PixieBrix has some additional constraints on which tabs can be accessed (i.e., only http/https)
canAccessTab: canAccessTab(target),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of waiting for each, sequential request, this triggers them in parallel and logs the navigation immediately, instead of possibly out of order.

Promises are still expandable in the console.

});
}

async function onNavigation({ tabId, frameId }: Target): Promise<void> {
if (syncFlagOn("navigation-trace")) {
await traceNavigation({ tabId, frameId });
}
}

// Some sites use the hash to encode page state (e.g., filters). There are some non-navigation scenarios where the hash
// could change frequently (e.g., there is a timer in the state). Debounce to avoid overloading the messenger and
// contentScript.
const debouncedOnNavigation = debounce(onNavigation, 100, {
const debouncedTraceNavigation = debounce(traceNavigation, 100, {
leading: true,
trailing: true,
maxWait: 1000,
});

function initNavigation(): void {
// Let the content script know about navigation from the history API. Required for handling SPA navigation
browser.webNavigation.onHistoryStateUpdated.addListener(onNavigation);
async function initNavigation(): Promise<void> {
if (!(await flagOn("navigation-trace"))) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this flag defined? This is the only mention in both the extension and the app. I thought this was connected to the "performanceTracing" skunkworks toggle but it's not.

Untested for this reason

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's defined and managed in the Django Admin for App.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's defined and managed in the Django Admin for App.

Correct, it comes in via the /api/me/ API endpoint

return;
}

browser.webNavigation.onHistoryStateUpdated.addListener(
debouncedTraceNavigation,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated this to use debouncing too

);
browser.webNavigation.onReferenceFragmentUpdated.addListener(
debouncedOnNavigation,
debouncedTraceNavigation,
);
}

Expand Down
5 changes: 2 additions & 3 deletions src/contentScript/contentScriptCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import registerMessenger from "@/contentScript/messenger/registration";
import registerBuiltinBricks from "@/bricks/registerBuiltinBricks";
import registerContribBlocks from "@/contrib/registerContribBlocks";
import brickRegistry from "@/bricks/registry";
import { handleNavigate, initNavigation } from "@/contentScript/lifecycle";
import { initNavigation } from "@/contentScript/lifecycle";
import { initTelemetry } from "@/background/messenger/api";
import { ENSURE_CONTENT_SCRIPT_READY } from "@/contentScript/ready";
import { initToaster } from "@/utils/notify";
Expand Down Expand Up @@ -65,8 +65,7 @@ export async function init(): Promise<void> {
initTelemetry();
initToaster();

await handleNavigate();
initNavigation();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

initNavigation should deal with this directly

Kinda suggested here: #7030 (comment)

void initNavigation();

void initSidebarActivation();

Expand Down
79 changes: 50 additions & 29 deletions src/contentScript/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ import * as sidebar from "@/contentScript/sidebarController";
import { NAVIGATION_RULES } from "@/contrib/navigationRules";
import { testMatchPatterns } from "@/bricks/available";
import reportError from "@/telemetry/reportError";
import { compact, groupBy, intersection, uniq } from "lodash";
import { compact, debounce, groupBy, intersection, uniq } from "lodash";
import oneEvent from "one-event";
import { resolveExtensionInnerDefinitions } from "@/registry/internal";
import { traces } from "@/background/messenger/api";
import { isDeploymentActive } from "@/utils/deploymentUtils";
import { PromiseCancelled } from "@/errors/genericErrors";
import { type FrameTarget, getThisFrame } from "webext-messenger";
import { getThisFrame } from "webext-messenger";
import { type StarterBrick } from "@/types/starterBrickTypes";
import { type UUID } from "@/types/stringTypes";
import { type RegistryId } from "@/types/registryTypes";
Expand Down Expand Up @@ -77,9 +78,9 @@ const _editorExtensions = new Map<UUID, StarterBrick>();
const _activeExtensionPoints = new Set<StarterBrick>();

/**
* Mapping from frame ID to URL. Used to ignore navigation events that don't change the URL.
* Used to ignore navigation events that don't change the URL.
*/
const _frameHref = new Map<number, string>();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The content script runs in a single frame. The frameId is always the same.

let lastUrl: string | undefined;

/**
* Abort controllers for navigation events for Single Page Applications (SPAs).
Expand Down Expand Up @@ -560,30 +561,18 @@ export async function handleNavigate({
force,
}: { force?: boolean } = {}): Promise<void> {
const runReason = decideRunReason({ force });

let thisTarget: FrameTarget;
try {
// Note: We used to check for invalid (undefined) frameId after calling
// this, but now getThisFrame will throw an error itself internally if
// the frameId is not a valid number. An example situation where this
// happens is when the dynamic gsheets code loads a frame within the
// extension background page.
thisTarget = await getThisFrame();
} catch (error: unknown) {
console.debug("Ignoring handleNavigate because getThisFrame failed", error);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If that happens, that's a setup error. We fixed this specific issue in:

Also in MV3 iframes cannot load in the background page at all.

return;
}

const thisTarget = await getThisFrame();
const { href } = location;

if (!force && _frameHref.get(thisTarget.frameId) === href) {
console.debug("Ignoring NOOP navigation to %s", href, thisTarget);
if (!force && lastUrl === href) {
console.debug(
"handleNavigate:Ignoring NOOP navigation to %s",
href,
thisTarget,
);
return;
}

_frameHref.set(thisTarget.frameId, href);

console.debug("Handling navigation to %s", href, thisTarget);
console.debug("handleNavigate:Handling navigation to %s", href, thisTarget);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Easy log filtering when all the logs have the same prefix

date

updateNavigationId();
notifyNavigationListeners();

Expand Down Expand Up @@ -639,9 +628,41 @@ export async function reactivateTab(): Promise<void> {
await handleNavigate({ force: true });
}

export function initNavigation() {
window.navigation?.addEventListener("navigate", async (event) => {
// Delay slightly to avoid catching events that navigate away from the page
setTimeout(handleNavigate, 0);
});
// Ideally we only want to catch local URL changes, but there's no way to discern
// navigation events that cause the current document to unload in the `navigate ` event.
async function onNavigate(event: NavigateEvent): Promise<void> {
if (
// Ignore navigations to external pages
!event.destination.url.startsWith(location.origin) ||
// Ignore <a download> links
event.downloadRequest !== null // Specifically `null` and not `''`
) {
return;
}

try {
await oneEvent(window, "beforeunload", {
signal: AbortSignal.timeout(0),
});
} catch {
// It timed out before the "beforeunload" event, so this is a same-document navigation
await handleNavigate();
}
}

export async function initNavigation() {
// Initiate PB for the current page
await handleNavigate();

// Listen to page URL changes
// Some sites use the hash to encode page state (e.g., filters). There are some non-navigation scenarios
// where the hash could change frequently (e.g., there is a timer in the state). Debounce to avoid overloading.
window.navigation?.addEventListener(
"navigate",
debounce(onNavigate, 100, {
leading: true,
trailing: true,
maxWait: 1000,
}),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I copied the debouncing and its comment from the original background listeners.

);
}
Loading