本文介绍了如何覆盖JavaScript Web API通知对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我需要打开和关闭在电子窗口内的Web视图中加载的网页的通知.为此,我在Web视图中注入了一个预加载文件,该文件将覆盖这样的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对象,以便可以禁用通知并具有原始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通知对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 04:42