By default, a WKWebView does not receive mouse events when it is not focused. However, you can use JavaScript to capture mouse movements on the webpage, even when the WKWebView is not focused. Here's how you can achieve this:

  1. Set up your WKWebView and load a webpage:
import WebKit

class ViewController: NSViewController, WKUIDelegate {
    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView

        let url = URL(string: "https://www.example.com")!
        let request = URLRequest(url: url)
        webView.load(request)
    }
}
  1. Inject JavaScript code into the webpage to capture mouse movements:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    let javascript = """
        document.addEventListener('mousemove', function(event) {
            // Send the mouse position to the native code
            window.webkit.messageHandlers.mouseMoved.postMessage({ x: event.clientX, y: event.clientY });
        });
    """

    webView.evaluateJavaScript(javascript, completionHandler: nil)
}
  1. Set up a message handler in your WKWebView to receive the mouse movement data:
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    webView.configuration.userContentController.add(self, name: "mouseMoved")
}

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if message.name == "mouseMoved", let data = message.body as? [String: CGFloat] {
        let x = data["x"] ?? 0
        let y = data["y"] ?? 0

        // Do something with the mouse movement data
        print("Mouse moved to \(x), \(y)")
    }
}

Now, the WKWebView will capture mouse movements on the webpage even when it is not focused. The JavaScript code will send the mouse position to the native code, which can then be processed and used as needed


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

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