user5857112
user5857112

Reputation: 21

Does WKWebView support loading of external javascript files?

I'm loading a html template into WKWebView. The HTML has a script tag which refers to a local JS file as mentioned below:

<script type="text/javascript" src="test.js"></script>

But, this js content is not getting loaded into web view at all.

So, i used WKUserScript to inject the content of this file into web view. This resolved my initial problem. But, i'm injecting some additional JS files in 'test.js' at run time. None of these files are getting loaded into web view.

When debugged, i get following error for all these files: 'Failed to load resource: The requested URL was not found on this server.'.

Interestingly, same code works fine when UIWebView is used.

Any input/feedback is appreciated. Thanks.

Upvotes: 2

Views: 3806

Answers (1)

Jason Honcheung Wong
Jason Honcheung Wong

Reputation: 65

Yes it can.

  1. load your test.js from Resources bundle

    var path = NSBundle.mainBundle().pathForResource("test", ofType: "js")

  2. Convert the file contents to a string, then use the built-in evaluateJavaScript() to load javascript code...

    webView.evaluateJavaScript(String.stringWithContentsOfFile(path), completionHandler: nil)

Upvotes: 3

Related Questions