【问题标题】:How to capture notifications in a WKWebView?如何在 WKWebView 中捕获通知?
【发布时间】:2018-07-18 05:57:29
【问题描述】:

我正在使用 Swift 4 开发 macOS 桌面应用程序。
它有一个 WKWebView 加载一个发送通知的网页。
默认情况下不显示任何通知,也没有权限请求。

我需要一种方法来显示通知并拦截它们,以便我可以显示一个计数器。

知道如何实现这一目标吗?

【问题讨论】:

  • 找到解决方案了吗?
  • @MICKAELBELHASSEN 恐怕不会

标签: swift macos webkit web-notifications


【解决方案1】:

我遇到了同样的挑战,并通过注入一个脚本 (WKUserScript) 解决了这个问题,该脚本使用自定义实现覆盖 Web 通知 API,该实现利用 WKUserContentController 将消息发送到发布最终通知的本机应用程序代码最后。

设置WKWebView

据我所知,WKWebView 的编程创建是使用自定义 WKWebViewConfiguration 所必需的。创建一个新的 macOS 应用程序项目,我在 ViewController 函数中扩展我的 viewDidLoad,如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

    let userScriptURL = Bundle.main.url(forResource: "UserScript", withExtension: "js")!
    let userScriptCode = try! String(contentsOf: userScriptURL)
    let userScript = WKUserScript(source: userScriptCode, injectionTime: .atDocumentStart, forMainFrameOnly: false)
    let configuration = WKWebViewConfiguration()
    configuration.userContentController.addUserScript(userScript)
    configuration.userContentController.add(self, name: "notify")

    let documentURL = Bundle.main.url(forResource: "Document", withExtension: "html")!
    let webView = WKWebView(frame: view.frame, configuration: configuration)
    webView.loadFileURL(documentURL, allowingReadAccessTo: documentURL)

    view.addSubview(webView)
}

首先,我从应用程序包中加载用户脚本并将其添加到用户内容控制器。我还添加了一个名为 notify 的消息处理程序,可用于从 JavaScript 上下文回拨到本机代码。最后,我从应用程序包中加载一个示例 HTML 文档,并使用窗口中可用的整个区域呈现 Web 视图。

覆盖通知 API

这是注入的用户脚本和网络Notification API 的部分覆盖。处理the typical notification permission request process 并在此通用问题范围内发布通知就足够了。

/**
 * Incomplete Notification API override to enable native notifications.
 */
class NotificationOverride {
    // Grant permission by default to keep this example simple.
    // Safari 13 does not support class fields yet, so a static getter must be used.
    static get permission() {
        return "granted";
    }

    // Safari 13 still uses callbacks instead of promises.
    static requestPermission (callback) {
        callback("granted");
    }

    // Forward the notification text to the native app through the script message handler.
    constructor (messageText) {
        window.webkit.messageHandlers.notify.postMessage(messageText);
    }
}

// Override the global browser notification object.
window.Notification = NotificationOverride;

每次在 JavaScript 上下文中创建新通知时,都会调用用户内容控制器消息处理程序。

处理脚本消息

ViewController(或任何其他应处理脚本消息的)需要符合WKScriptMessageHandler 并实现以下函数来处理调用:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let content = UNMutableNotificationContent()
        content.title = "WKWebView Notification Example"
        content.body = message.body as! String

        let uuidString = UUID().uuidString
        let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: nil)

        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.add(request) { (error) in
            if error != nil {
                NSLog(error.debugDescription)
            }
        }
    }

整个实现是关于在 macOS 中创建本地的原生通知。但是,如果不付出额外的努力,它还不能工作。

应用代理调整

在允许 macOS 应用发布通知之前,它必须请求这样做的权限,例如网站。

func applicationDidFinishLaunching(_ aNotification: Notification) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
    }

如果应在应用处于前台时显示通知,则必须进一步扩展应用委托以符合 UNUserNotificationCenterDelegate 并实现:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler(UNNotificationPresentationOptions.alert)
    }

这需要applicationDidFinishLaunching(_:)中的委托分配:

UNUserNotificationCenter.current().delegate = self

UNNotificationPresentationOptions 可能会根据您的要求而有所不同。

参考

我创建了an example project available on GitHub,它渲染了整个画面。

【讨论】:

  • 您的解决方案有效,但遗憾的是不适用于 WhatsApp 或 Facebook Messenger 等 Web 视图或大多数发送通知的网页。因为在发送通知之前,网页首先检查window.Notification.permissiondenied 还是enabled。因此,您的解决方案仅在理论上是好的,但在实际网页中您的解决方案无法使用。
  • 我扩展了用户脚本以涵盖通用授权过程。我最初认为这超出了范围,因为问题更多是关于通知的概念桥接。
  • @MickaelBelhassen 这是granted,而不是enabled(见the specification)。
  • 做得很好,我赞成。这是第一次有人为此发布解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
相关资源
最近更新 更多