如何覆盖 JavaScript web api 通知对象

时间:2023-01-28
本文介绍了如何覆盖 JavaScript web api 通知对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个场景,我需要为电子窗口内的 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 通知对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:create-react-app 排除文件夹触发重新加载 下一篇:Chrome/Firefox console.log 总是附加一行“未定义"

相关文章

最新文章