简体   繁体   English

WKWebView是否支持加载外部javascript文件?

[英]Does WKWebView support loading of external javascript files?

I'm loading a html template into WKWebView. 我正在将html模板加载到WKWebView中。 The HTML has a script tag which refers to a local JS file as mentioned below: HTML具有脚本标记,该标记引用如下所述的本地JS文件:

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

But, this js content is not getting loaded into web view at all. 但是,此js内容根本没有加载到Web视图中。

So, i used WKUserScript to inject the content of this file into web view. 因此,我使用WKUserScript将此文件的内容注入到Web视图中。 This resolved my initial problem. 这解决了我最初的问题。 But, i'm injecting some additional JS files in 'test.js' at run time. 但是,我在运行时在“ test.js”中注入了一些其他的JS文件。 None of these files are getting loaded into web view. 这些文件均未加载到Web视图中。

When debugged, i get following error for all these files: 'Failed to load resource: The requested URL was not found on this server.' 调试后,对于所有这些文件,我都会收到以下错误消息: “无法加载资源:在此服务器上找不到请求的URL。” .

Interestingly, same code works fine when UIWebView is used. 有趣的是,使用UIWebView时,相同的代码可以正常工作。

Any input/feedback is appreciated. 任何输入/反馈表示赞赏。 Thanks. 谢谢。

Yes it can. 是的,它可以。

  1. load your test.js from Resources bundle 从资源包中加载test.js

    var path = NSBundle.mainBundle().pathForResource("test", ofType: "js") 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... 将文件内容转换为字符串,然后使用内置的validateJavaScript()加载javascript代码...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM