Skip to content

Instantly share code, notes, and snippets.

@estruyf
Created September 11, 2019 11:00
Show Gist options
  • Select an option

  • Save estruyf/d81bb50b7596dceb2552a6b5d02ef576 to your computer and use it in GitHub Desktop.

Select an option

Save estruyf/d81bb50b7596dceb2552a6b5d02ef576 to your computer and use it in GitHub Desktop.
Browser history binding
/**
* Bind the control to the browser history to do metadata check when page is in edit mode
*/
private bindToHistory(): void {
// Only need to bind the pushState once to the history
if (!this.pushState) {
// Binding to page mode changes
this.pushState = () => {
const defaultPushState = history.pushState;
// We need the current this context to update the component its state
const self = this;
return function (data: any, title: string, url?: string | null) {
console.log("bindToHistory:", url);
// Check if you navigated to a new page creation
if (url.indexOf("newpage.aspx")) {
// Check if the page is in edit mode
if (url.toLowerCase().indexOf('mode=edit') !== -1) {
self.isNewPage = true;
} else if (self.isNewPage) {
// Page is created
self.handleNewPageReload();
}
} else if (self.isNewPage) {
// Page is created
self.handleNewPageReload();
}
// Call the original function with the provided arguments
// This context is necessary for the context of the history change
return defaultPushState.apply(this, [data, title, url]);
};
};
history.pushState = this.pushState();
}
}
/**
* New page reload handler
*/
private handleNewPageReload(count: number = 0) {
this.isNewPage = false;
const crntHref = location.href.toLowerCase();
console.log("handleNewPageReload:", crntHref);
if (crntHref.indexOf("newpage.aspx") !== -1 || crntHref.indexOf("mode=edit") !== -1) {
if (count < 5) {
setTimeout(() => {
this.handleNewPageReload(++count);
}, 50);
}
} else {
// The page is ready to be reloaded
location.reload();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment