Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Javascript into Webview - Swift

How can I inject javascript into a webview (IOS/Swift) after loading some custom html.

@IBOutlet weak var webView: UIWebView!

var html = "<div id='test'></div>"

self.webview.loadHTMLString(html, baseURL: nil)

I want to inject the following javascript into the webview after I load my custom html.

var myelement = document.getElementById("test");
myelement.innerHTML= "New Text";
like image 764
user2423476 Avatar asked Feb 02 '17 07:02

user2423476


People also ask

How do I inject JavaScript into Webview react native?

Use injectJavaScript as per (Guide > Communicating between JS and Native > The injectJavaScript method)[https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#the-injectjavascript-method"]. In your case, that would be something like this. webview. injectJavaScript(jsCode)

What is WKWebView?

A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.

What is window Webkit Messagehandlers?

A message handler is a listener that will fire and return data once some JavaScript event completes. For example, you can have a handler to parse JSON data fetched from a URL. By including these message handlers into your WKUserContentController object, your web view will define a new function window. webkit.


1 Answers

Just do:

let js = "var myelement = document.getElementById(\"test\");myelement.innerHTML= \"New Text\";"
webView.evaluateJavaScript(js, completionHandler: nil)

If you are using UIWebView instead of WKWebView, do this:

let js = "var myelement = document.getElementById(\"test\");myelement.innerHTML= \"New Text\";"
_ = webView.stringByEvaluatingJavaScript(from: js)
like image 99
Sweeper Avatar answered Oct 13 '22 23:10

Sweeper