@corvina/corvina-app-connect
Version:
This library enables an application embedded as an iframe in Corvina to retrieve some information such as JWT, organization id, ...
68 lines • 2.86 kB
JavaScript
import { appHrefQueryString } from "./common";
export class UrlWatcher {
constructor(onUrlChange, currentWindow) {
this._window = window;
this._window = currentWindow || window;
this._onUrlChange = onUrlChange;
this._originalPushState = this._window.history.pushState;
this._originalReplaceState = this._window.history.replaceState;
this._window.history.pushState = (...args) => {
this._originalPushState.apply(this._window.history, args);
this._onUrlChange({ type: 'pushState' });
};
this._window.history.replaceState = (...args) => {
this._originalReplaceState.apply(this._window.history, args);
this._onUrlChange({ type: 'replaceState' });
};
this._window.addEventListener("popstate", this._onUrlChange);
}
dispose() {
this._window.history.pushState = this._originalPushState;
this._window.history.replaceState = this._originalReplaceState;
this._window.removeEventListener("popstate", this._onUrlChange);
}
static extractAppHref() {
try {
const url = new URL(window.location.href);
let appHref = url.searchParams.get(appHrefQueryString);
if (!appHref) {
appHref = (new URLSearchParams(url.hash.slice(url.hash.indexOf('?')))).get(appHrefQueryString);
}
if (appHref) {
return decodeURIComponent(appHref);
}
}
catch (error) {
console.warn("CorvinaHost: Error extracting appHref from ", window.location.href);
}
return undefined;
}
setAppHref(appHref, type) {
const applyPath = (path) => {
if (type === 'replaceState') {
this._originalReplaceState.call(this._window.history, null, "", path);
}
else {
this._originalPushState.call(this._window.history, null, "", path);
}
};
if (this._window.location.hash) {
let queryParamsPos = this._window.location.hash.indexOf("?");
if (queryParamsPos < 0) {
applyPath(this._window.location.hash + "?" + appHrefQueryString + "=" + encodeURIComponent(appHref));
}
else {
const params = new URLSearchParams(this._window.location.hash.slice(queryParamsPos));
params.set(appHrefQueryString, appHref);
const newHash = this._window.location.hash.slice(0, queryParamsPos + 1) + params;
applyPath(newHash);
}
}
else {
const url = new URL(this._window.location.href);
url.searchParams.set(appHrefQueryString, appHref);
applyPath(url.toString());
}
}
}
//# sourceMappingURL=hrefwatcher.js.map