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";
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)
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With