我需要从我的应用程序资源文件夹加载 javascript 文件。截至目前,它确实可以很好地从资源中读取图像,但由于某种原因它无法读取 javascript。
如果将 html 文件本身写入资源,我已经能够呈现引用这些 javascript 的 html 文档,但我想通过设置 UIWebView 的 html 来呈现 html/js,以便它可以是动态的。
这是我正在做的:
NSString * html = @"<!DOCTYPE html><html><head><title>MathJax</title></head><body><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script><script type=\"text/javascript\" src=\"/MathJax/MathJax.js\"></script>$$\\int_x^y f(x) dx$$<img src=\"coffee.png\"></body></html>";
NSString * path = [[NSBundle mainBundle] resourcePath];
path = [path stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString * resourcesPath = [[NSString alloc] initWithFormat:@"file://%@/", path];
[webview loadHTMLString:html baseURL:[NSURL URLWithString:resourcesPath]];
现在,如果我将基本 URL 更改为我的服务器,它也有所需的文件,它会正确加载。如果不需要互联网连接就好了。任何帮助表示赞赏! ;)
我发现这对显示图像很有用:iPhone Dev: UIWebView baseUrl to resources in Documents folder not App bundle
编辑:
我没有进行字符串替换和 URL 编码,而是通过简单地调用 mainBundle 上的 resourceURL 来获取图像,但仍然没有执行 javascript。
NSString * setHtml = @"<!DOCTYPE html><html><head><title>MathJax</title></head><body><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script><script type=\"text/javascript\" src=\"/MathJax/MathJax.js\"></script>$$\\int_x^y f(x) dx$$<img src=\"images/test.png\"></body></html>";
[webview loadHTMLString:setHtml baseURL:[[NSBundle mainBundle] resourceURL]];
编辑
如果您想尝试一下,我已经创建了一个示例项目,让您更轻松!
https://github.com/pyramation/math-test
git clone git@github.com:pyramation/math-test.git
最佳答案
这里我们进行一个简单的设置。
在您的 Resources 文件夹中创建以下文件夹结构。
请注意,蓝色文件夹是引用的文件夹
css 只是糖果 :) 在 lib.js 中驻留着您想要使用的 javascript 代码。
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/standard.css">
<script src="js/lib.js" type="text/javascript" />
</head>
<body>
<h2>Local Javascript</h2>
<a href="javascript:alert('Works!')">Test Javascript Alert</a>
<br/>
<br/>
<a href="javascript:alertMeWithMyCustomFunction('I am');">External js test</a>
</body>
</html>
lib.js
function alertMeWithMyCustomFunction(text) {
alert(text+' -> in lib.js');
}
在 webview 中加载内容
注意:webView是一个属性,view是用instance builder创建的
- (void)viewDidLoad
{
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index"
ofType:@"html"
inDirectory:@"/htdocs" ];
NSString *html = [NSString stringWithContentsOfFile:htmlPath
encoding:NSUTF8StringEncoding
error:nil];
[webView loadHTMLString:html
baseURL:[NSURL fileURLWithPath:
[NSString stringWithFormat:@"%@/htdocs/",
[[NSBundle mainBundle] bundlePath]]]];
}
这应该是结果:
编辑:
snowman4415 提到 iOS 7 不喜欢自动关闭标签脚本标签,所以如果某些东西在 iOS 7 上不起作用,您可能需要使用 </script>
关闭标签。
关于javascript - 从资源中将 javascript 加载到 UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5733883/