I have a scenario where I need to toggle notifications on and off for a webpage that is loaded in a webview inside an electron window. To do that I have injected a preload file inside the webview that overrides the Notification object like this.
window.oldNotification = window.Notification;
window.Notification = function() {
let notificationEnabled = localStorage.getItem('notification-permissions') === 'true';
if (notificationEnabled) {
new window.oldNotification(...arguments);
}
};
I am enabling and disabling notifications by changing a local storage variable.
The issue is that the webpage that I want to control is using Notification.permission method (refer this). Now my new Notification object has no permission property on it. I am not able to override the Notification object in a way where I can update its constructor so that I can disable the notification and also have other properties of the original Notification object.
Is there a way to achieve this or is this not possible at all? Any help or suggestion is absolutely welcome.
You can easily emulate Notification API
window.Notification = function() {
const notificationEnabled = Notification.permission === 'granted';
return notificationEnabled ? new window.oldNotification(...arguments) : {};
};
Object.defineProperty(Notification, 'permission', {
get() {
return localStorage.getItem('notification-permissions') === 'true' ? 'granted' : 'denied';
}
});
Notification.requestPermission = (callback) => {
if (typeof callback === 'function') {
callback(Notification.permission);
}
return Promise.resolve(Notification.permission);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With