Unfortunately, it is not possible to directly receive mouse movements on a WKWebView when it is not the current window or in focus. The WKWebView and its underlying web content are designed to interact with user input only when it is the active window or in focus.

However, if you have control over the web page content loaded in the WKWebView, you can implement a workaround using JavaScript to capture mouse movements and send them to your app via JavaScript bridge or message handler. Here's an example of how you can achieve this:

  1. Inject JavaScript into the WKWebView:
let script = """
window.addEventListener('mousemove', function(event) {
    window.webkit.messageHandlers.mouseMovement.postMessage({
        x: event.clientX,
        y: event.clientY
    });
});
"""
let userScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
webView.configuration.userContentController.addUserScript(userScript)
  1. Set up a message handler in your app:
webView.configuration.userContentController.add(self, name: "mouseMovement")
  1. Implement the WKScriptMessageHandler protocol in your view controller:
extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "mouseMovement", let body = message.body as? [String: CGFloat] {
            let x = body["x"] ?? 0
            let y = body["y"] ?? 0
            // Handle the mouse movement coordinates
            print("Mouse moved to (\(x), \(y))")
        }
    }
}

By injecting JavaScript into the web page loaded in the WKWebView and setting up a message handler, you can capture mouse movement events and receive them in your app. However, please note that this approach requires control over the web page content and may not work for all scenarios

how to make WKWebViews current webpage to receive mouse movements when its not the current window

原文地址: http://www.cveoy.top/t/topic/i0cB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录