最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Call swift function with javascript using UIWebview - Stack Overflow

programmeradmin3浏览0评论

I apologize if this has been asked but I was unable to find any answer or solution. I am looking to call a JavaScript function from a "UIWebView" and listen for it in swift. Any example I have found uses "WKWebView". There has to be an easy way to listen to a JavaScript function like the below:

// HTML / JS
<div id ="myDiv" onclick="listenInSwift()">myItem</div>

Is this possible with a UIWebView? Thanks all!

I apologize if this has been asked but I was unable to find any answer or solution. I am looking to call a JavaScript function from a "UIWebView" and listen for it in swift. Any example I have found uses "WKWebView". There has to be an easy way to listen to a JavaScript function like the below:

// HTML / JS
<div id ="myDiv" onclick="listenInSwift()">myItem</div>

Is this possible with a UIWebView? Thanks all!

Share Improve this question asked Mar 21, 2016 at 18:37 user3612986user3612986 3252 gold badges7 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

Implement listenInSwift like this:

function listenInSwift() {
    window.location = 'yoururlscheme://somehost?greeting=hello'
} 

Then listen for this URL with this code in your UIWebViewDelegate class:

func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType navigationType: UIWebViewNavigationType) -> Bool {
    if request.URL.scheme == 'yoururlscheme' {
        print('Hello JavaScript...')
    }
}

Don't forget to register your URL Scheme (in this case 'yoururlscheme') in Xcode.

To load a local file in the web view, try this:

let baseURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath);
let relativePath = "www/\(file)"
let fileURL = NSURL(string: relativePath, relativeToURL: baseURL);
let URLRequest = NSURLRequest(URL: fileURL!);
webView.loadRequest(URLRequest)

this worked fine for me:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if request.url?.scheme == ".example.app" {
        print("I’m some JavaScript hoho")
    }

    return true
}

Note: you have to add ".example.app" or whatever in your xcode project settings. Go to info, scroll down and find URL Scheme. Add your desired scheme there. Leave the other stuff the way it is. Then it should work just fine.

发布评论

评论列表(0)

  1. 暂无评论