How do I get Swift to run a Webview Javascript?

Asked 1 years ago, Updated 1 years ago, 67 views

I would like to run the following Javascript in the webview in the UIButton written in Swift, but could you help me?

Javascript side

function show()
{
alert("Run JavaScript";←I want to do this on Swift
}

Swift side import UIKit
import JavaScriptCore

classViewController:UIViewController, UIWebViewDelegate {

var webView:UIWebView=UIWebView()

}

button.addTarget(self, action: "pushBtn:", forControlEvents: .TouchUpInside)

func pushBtn (sender:AnyObject) {

// Now I want to write a code to call the function show() of the webview.

    // Alert notes in Swift below
    let alert=UIAlertView()
    alert.title="Swift"
    alert.message="Alert on Swift"
    alert.addButtonWithTitle("OK")
    alert.show()
}

javascript ios swift xcode

2022-09-30 21:12

1 Answers

Is the webview from UIWebView (not WKWebView)?They didn't even write down how to declare the properties with the webview, so please feel free to do so

@IBOutlet var webView:UIWebView!

Although declared as a property in the form shown in , UIWebView has exactly the method for executing JavaScript code.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString:
If the function is defined at the time of call, you can call the function, so you just write it like this.

webView.stringByEvaluingJavaScriptFromString("show();")


2022-09-30 21:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.