Related to
I'm trying to have my sub-classed WkWebView act on middle button URL click to present the link in a new window/webView. WkWebView's contextual menu features an item to do this - whose target/action I alter to my view, but I'd like the simplicity as in web browsers to do the same; middle button yields new window.
I'd have this so far:
viewDidLoad() {
// Watch javascript selection messages
let controller = webView.configuration.userContentController
controller.add(self, name: "newWindowWithUrlDetected")
let js = """
// https://stackoverflow.com/questions/50846404/how-do-i-get-the-selected-text-from-a-wkwebview-from-objective-c
function getSelectionAndSendMessage()
{
var txt = document.getSelection().toString() ;
window.webkit.messageHandlers.newSelectionDetected.postMessage(txt) ;
}
document.onmouseup = getSelectionAndSendMessage ;
document.onkeyup = getSelectionAndSendMessage ;
// https://stackoverflow.com/questions/21224327/how-to-detect-middle-mouse-button-click/21224428
document.body.onclick = function (e) {
if (e && (e.which == 2 || e.button == 4 )) {
middleLink;
}
}
function middleLink()
{
window.webkit.messageHandlers.newWindowWithUrlDetected.postMessage(this.href) ;
}
// https://stackoverflow.com/questions/51894733/how-to-get-mouse-over-urls-into-wkwebview-with-swift/51899392#51899392
function sendLink()
{
window.webkit.messageHandlers.newUrlDetected.postMessage(this.href) ;
}
var allLinks = document.links;
for(var i=0; i< allLinks.length; i++)
{
allLinks[i].onmouseover = sendLink ;
}
"""
let script = WKUserScript.init(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
controller.addUserScript(script)
}
The idea was that on a mouse over, the link would be reported but when the action takes place I'd like to know which button was sent to the view.
The trouble is that I'm not seeing the action, not in my decision handler; even an override on load(URLRequest:) itself
override func load(_ request: URLRequest) -> WKNavigation? {
Swift.print("we got \(request)")
return super.load(request)
}
Since I'm not getting the action I suppose the issue is the javascrpt is not "sending" such an event and being handled entirely within the webpage?
How can this event's button be make known to its view?
Nav delegate apparently not working?
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let event = NSApp.currentEvent, event.buttonNumber <= 1 else {
if let url = navigationAction.request.url {
Swift.print("newWindow with url:\(String(describing: url))")
DispatchQueue.main.async {
self.appDelegate.openURLInNewWindow(url)
}
}
decisionHandler(WKNavigationActionPolicy.cancel)
return
}
decisionHandler(WKNavigationActionPolicy.allow)
return
}