UIWebview open URL in mobile safari using javascri

2019-05-22 10:11发布

问题:

So I'm building an HTML5 game using phaser and I have a button that calls a URL in javascript like this:

window.open("http://google.com", "_blank"); 

This works great on desktop opening in a new window, I'm also able to get it to open in the default browser on an android device via webview as well. But on iOS using a UIWebView in swift I'm using the following code

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
        if navigationType == UIWebViewNavigationType.LinkClicked {
            UIApplication.sharedApplication().openURL(request.URL)
            return false
        }
        return true
    }

It triggers so yes I have the delegate set, I even have a breakpoint in here so I could look through the properties, and request.URL is nowhere to be found. None of these properties have a URL I can use to detect and call mobile safari...

Everything I've found online just says it's only known to work with standard link tags like <a href="http://google.com">link text</a> I also tried document.location.href = "http://google.com"; with no luck. Btw, I did test with <a href="http://google.com">link text</a> and this function works, it makes it open in safari. It just doesn't work when the URL is called via Javascript.

Also, webViewDidStartLoad/webViewDidFinishLoad both trigger breakpoints when the URL is called yet there is no URL anywhere to be found in any of the properties provided in the webView object...

Any ideas how I can get the delegate functions to play well with with javascript calling the URL? Or any ideas for work arounds? It's just loading the link inside the webview... I just need it to open those links in mobile safari.

回答1:

Figured it out! Just make an empty a tag somewhere on your html page that conatins the game content like:

<a id="theLink" target="_blank" href="http://google.com"></a>

Then "click" it using Javascript like this:

document.getElementById('theLink').click();

That used in conjunction with the swift code above is working for me and the game opens the link in safari.