問題描述
我有一個場景,我需要為電子窗口內的 web 視圖中加載的網頁打開和關閉通知.為此,我在 webview 中注入了一個 preload 文件,它像這樣覆蓋 Notification 對象.
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.
問題是我要控制的網頁正在使用 Notification.permission
方法 (參考這里).現在我的新通知對象上沒有權限屬性.我無法以可以更新其構造函數的方式覆蓋 Notification 對象,以便我可以禁用通知并擁有原始 Notification 對象的其他屬性.
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.
推薦答案
您可以輕松模擬 Notification API
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);
};
這篇關于如何覆蓋 JavaScript web api 通知對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!