将本地 javascript 注入 UIWebView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7312584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inject a local javascript into UIWebView
提问by James
Is there a way to inject a local JS file or a JS file that's store on my server into any web page loaded by UIWebView?
有没有办法将本地 JS 文件或存储在我的服务器上的 JS 文件注入到 UIWebView 加载的任何网页中?
Say I navigate to google.com in that UIWebView, it renders that page and also runs my JS file (local or on my webserver)?
假设我在该 UIWebView 中导航到 google.com,它呈现该页面并运行我的 JS 文件(本地或在我的网络服务器上)?
回答by Sherman Lo
The following code will inject javascript locally
以下代码将在本地注入javascript
- (void)injectJavascript:(NSString *)resource {
NSString *jsPath = [[NSBundle mainBundle] pathForResource:resource ofType:@"js"];
NSString *js = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:NULL];
[self.webView stringByEvaluatingJavaScriptFromString:js];
}
Just pass in the name of the file before the js, eg.
只需在js之前传入文件名,例如。
[self injectJavascript:@"script"];
To do inject javascript from your server you can download it first and load it into the web view in a similar manner.
要从您的服务器注入 javascript,您可以先下载它并以类似的方式将其加载到 Web 视图中。
回答by Alexander Larionov
Would like to complete Sherman's answer. Xcode defines *.js - files as source code and adds it to "Compile Sources" in project preferences, so objc returns nil, when you try to get pathForResource in mainBundle. To fix this issue you have to add your JavaScript file to "Build Phases" > "Copy Bundle Resources" in project preferences. Hope it would be helpful, faced this problem today.
想完成谢尔曼的回答。Xcode 将 *.js - 文件定义为源代码并将其添加到项目首选项中的“编译源”中,因此当您尝试在 mainBundle 中获取 pathForResource 时,objc 返回 nil。要解决此问题,您必须将 JavaScript 文件添加到项目首选项中的“构建阶段”>“复制捆绑资源”。希望它会有所帮助,今天遇到了这个问题。