如何覆盖 JavaScript web api 通知对象

How to override JavaScript web api Notification object(如何覆盖 JavaScript web api 通知对象)
本文介绍了如何覆盖 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 通知对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

opening html from google drive(从谷歌驱动器打开 html)
Google apps script get range of bytes from binary file(谷歌应用程序脚本从二进制文件中获取字节范围)
Sending Multiple attachments with Google Script from Google Drive(使用 Google 脚本从 Google Drive 发送多个附件)
Distributing Google Apps Scripts for Sheets in your company network(在您的公司网络中分发适用于表格的 Google Apps 脚本)
Upload file to my google drive from anyone using javascript(使用 javascript 将文件从任何人上传到我的谷歌驱动器)
quot;Shared Drivequot; support in Google Apps Script(“共享驱动器Google Apps 脚本中的支持)