Skip to content

Commit

Permalink
Trigger the URL_CHANGED event only if from/to URL are different (#516)
Browse files Browse the repository at this point in the history
Check if from/to URL are different after removing `?readthedocs-diff=`
attribute because we don't want to trigger the even when the user
enabled
docdiff in the current page.

Closes #506
  • Loading branch information
humitos authored Feb 4, 2025
1 parent 24e8240 commit d1c96fe
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
4 changes: 3 additions & 1 deletion src/linkpreviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,9 @@ export class LinkPreviewsElement extends LitElement {

_handleRootDOMChanged = (e) => {
// Trigger the setup again since the DOM has changed
this.setupTooltips();
if (this.config) {
this.setupTooltips();
}
};

connectedCallback() {
Expand Down
21 changes: 18 additions & 3 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,9 @@ export function setupHistoryEvents() {
for (const methodName of ["pushState", "replaceState"]) {
const originalMethod = history[methodName];
history[methodName] = function () {
// Save the from URL to compare against before triggering the event.
const fromURL = new URL(window.location.href);

const result = originalMethod.apply(this, arguments);

// Dispatch the event only when the third argument (url) is passed.
Expand All @@ -222,9 +225,21 @@ export function setupHistoryEvents() {
// https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
// https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
if (arguments.length === 3) {
const event = new Event(EVENT_READTHEDOCS_URL_CHANGED);
event.arguments = arguments;
dispatchEvent(event);
const toURL = arguments[2];

// TODO: we can't import this here -- it has to be at the top.
// We can't import it at the top due to circular dependencies.
// I'm using the hardcoded name for now.
//
// import { DOCDIFF_URL_PARAM } from "./docdiff";
toURL.searchParams.delete("readthedocs-diff");

// Dispatch the event only if the new URL is not just the DOCDIFF_URL_PARAM added.
if (toURL.href !== fromURL.href) {
const event = new Event(EVENT_READTHEDOCS_URL_CHANGED);
event.arguments = arguments;
dispatchEvent(event);
}
}

return result;
Expand Down

0 comments on commit d1c96fe

Please sign in to comment.