suale-dev / JavaScriptInterface

Calling native code from Javascript in the iOS application likes addJavascriptInterface in the Android.
36 stars 9 forks source link

Problem in using #2

Closed SalvatoreAD closed 5 years ago

SalvatoreAD commented 7 years ago

Hi, I have problems capturing the JavaScript code. I use webview.loadrequest to load the site. The site is in WordPress. The libraries can not capture the Javascript code. Can you help me?

Thanks

suale-dev commented 7 years ago

@SalvatoreAD could you give me more detail about error? you couldn't call native function from javascript code?

SalvatoreAD commented 7 years ago

@sua8051 In iOS i call the site with loadrequest by passing a URL and setting the cookie. On the website are written the methods as Android form (Native.method)

As soon as the request is finished, I make addJavascriptInterface. The project does not make any mistakes, but as soon as I get to the webview, it does not capture the code.

I thought maybe because in the request path does not show any HTML files, maybe that's the problem

suale-dev commented 7 years ago

Could you give me your protocol inherit from JSExport && the class conform that?

SalvatoreAD commented 7 years ago

Unfortunately I am without a laptop at the moment. Cmq I used the files UiWebViewEXT.swift and JSInterface.swift

SalvatoreAD commented 7 years ago

JSInterface

`import Foundation import JavaScriptCore import UIKit

@objc protocol MyJSInterface : JSExport { func openChat(_ message: String) }

class JSInterface: NSObject, MyJSInterface { func openChat(_ message: String){ print("OpenChat Catturato") }

}`

this is the class of webview

`class WebHomeController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var loadingWebView: UIView!
@IBOutlet weak var loading_web: UIActivityIndicatorView!

let defaults = UserDefaults.standard

override func viewDidLoad() {
    super.viewDidLoad()
    loadingWebView.isHidden = true

    //Creazione WebView
    let req = NSURLRequest(url: NSURL(string: APIKey.test_url)! as URL)
    let cookie = defaults.object(forKey: "cookie") as! String
    let cookie_name = defaults.object(forKey: "cookie_name") as! String

    executeValidateRequest(cookie: cookie) { (response) in
        if(response.status == "ok" && response.valid == true){

            self.webView.delegate = self
            self.setCookie(key: cookie, value: cookie_name as AnyObject)
            let userAgent = self.webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")!
            let custom_agent = " DB_APP"
            let new_userAgent = "\(userAgent)\(custom_agent)"
            UserDefaults.standard.register(defaults: ["UserAgent" : new_userAgent])
            self.webView.loadRequest(req as URLRequest)
            self.loading_web.startAnimating()
            self.loadingWebView.isHidden = false

        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func webViewDidFinishLoad(_ webview: UIWebView){
    loading_web.stopAnimating()
    loadingWebView.isHidden = true
    webView.isHidden = false
    webView.addJavascriptInterface(object: JSInterface(), forKey: "JSInterface")
}

func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    loading_web.stopAnimating()
    loadingWebView.isHidden = true
}

/*func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.url?.path)
    return true
}*/

let ExpTime = TimeInterval(60 * 60 * 24 * 365)
func setCookie(key: String, value: AnyObject) {
    let cookieProps: [HTTPCookiePropertyKey : Any] = [
        HTTPCookiePropertyKey.domain: APIKey.test_url,
        HTTPCookiePropertyKey.path: "/",
        HTTPCookiePropertyKey.name: key,
        HTTPCookiePropertyKey.value: value,
        HTTPCookiePropertyKey.secure: "TRUE",
        HTTPCookiePropertyKey.expires: NSDate(timeIntervalSinceNow: ExpTime)
    ]

    if let cookie = HTTPCookie(properties: cookieProps) {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
}`
suale-dev commented 7 years ago

@SalvatoreAD put "webView.addJavascriptInterface(object: JSInterface(), forKey: "JSInterface")" at viewDidLoad, just bind one time please :) In your javascript code: you should call : JSInterface.openChat("Call function from Javascript") to perform func openChat(_ message: String)