9

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";
2
  • evaluate JavaScript, google that, it is hard to be easier to find Commented Feb 2, 2017 at 7:44
  • Possible duplicate of Inject a JavaScript code in Webview iOS Commented Feb 2, 2017 at 8:10

2 Answers 2

17

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)
Sign up to request clarification or add additional context in comments.

Comments

7

use WKWebview and use WKNavigationDelegate Delegate

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        let str = "setData(\"\(uid)\",\"\(DataProvider.sharedInstance.baseUrl)\")"
        self.webView.evaluateJavaScript(str) { (id, error) in
            print(error)
        }
    }

1 Comment

It's still there, just Swift 4-ized / modularized; try this signature: func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!). (Injecting the JS here does the job for me -- thanks!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.