3 回答

TA贡献1155条经验 获得超0个赞
这是将本地javascript文件注入到Web视图的DOM中的另一种方法。您将JS文件的内容加载到字符串中,然后使用stringByEvalutatingJavaScriptFromString:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *jsFile = @"jquery-1.8.2.min.js";
NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:nil];
NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];
NSString *javascriptCode = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:javascriptCode];
// ...
}
如果您不拥有要显示的* .html / xhtml文件(例如ePub阅读器或新闻聚合器),则此功能特别有用。它可以帮助您不必担心从xhtml文件到js文件的相对路径。

TA贡献1866条经验 获得超5个赞
这就是我使用Webview和本地JS的方式。把一些快照这里的示例项目在这里
// Get the path for index.html, where in which index.html has reference to the js files, since we are loading from the proper resource path, the JS files also gets picked up properly from the resource path.
func loadWebView(){
if let resourceUrl = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "WebDocs2"){
let urlRequest = URLRequest.init(url: resourceUrl)
myWebView.loadRequest(urlRequest)
}
}
// Load the JS from resources
func jsScriptText() -> String? {
guard let jsPath = Bundle.main.path(forResource: "hello", ofType: "js", inDirectory: "WebDocs2/scripts") else {
return nil
}
do
{
let jsScript = try String(contentsOfFile: jsPath, encoding: String.Encoding.utf8)
return jsScript
}catch{
print("Error")
return nil
}
}
// Run the java script
func runJS(){
if let jsScript = jsScriptText(){
let jsContext = JSContext()
_ = jsContext?.evaluateScript(jsScript)
let helloJSCore = jsContext?.objectForKeyedSubscript("helloJSCore")
let result = helloJSCore?.call(withArguments: [])
print(result?.toString() ?? "Error")
}
}
添加回答
举报