2011-04-20 100 views
22

我需要从我的应用程序资源文件夹加载JavaScript文件。截至目前,它确实从资源中读取图像,但由于某些原因,它不会读取JavaScript。从资源加载JavaScript到UIWebView

如果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编码,我是能够通过简单地调用resourceURL获得图像在mainBundle上,但仍然没有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 [email protected]:pyramation/math-test.git 
+2

我是有这个问题;解决方案是将JavaScript添加到Copy Bundle Resources构建阶段:http://stackoverflow.com/questions/843820/iphone-uiwebview-local-resources-using-javascript-and-handling-onorientationchang/851333#851333 – 2011-10-06 03:13:52

回答

49

在这里,我们去一个简单的设置。

在资源文件夹中创建以下文件夹结构。

注意,蓝色的文件夹被引用者

enter image description here

的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> 

库。在网页视图内容的JS

function alertMeWithMyCustomFunction(text) { 
    alert(text+' -> in lib.js'); 
} 

加载

注:Webview是一个属性,用实例建设者创建的视图

- (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]]]]; 
} 

,这应该是结果:

enter image description here enter image description here

编辑:

snowman4415提到的iOS 7不喜欢自我结束标记脚本标记,所以如果自己是不是在iOS 7的工作,你可能需要用</script>

+0

By你有没有尝试过我做的例子?这种方法似乎不起作用。我添加了[webview loadHTMLString:setHtml baseURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]]];没有运气。 – pyramation 2011-04-27 22:13:50

+0

@Nick在github链接上检查DynamicHTMLWebViewController.m,我把你的建议放在那里。你可以看一下吗? – pyramation 2011-04-27 22:17:18

+0

@pyramation,我正在寻找。 – 2011-04-28 07:32:18

14

这里关闭标签是将本地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文件的相对路径。

+0

好!最后得到它 – brbgyn 2015-07-14 18:42:45

+0

在最新的Swift版本中,这将等同于什么? – ShP 2016-03-07 00:49:41

+0

CSS文件怎么样? – AsifHabib 2017-02-06 19:34:25

2

这是我如何使用Webview和本地JS。把一些快照这里的示例项目here

Resources

// 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") 

    } 
} 
+1

非常感谢这项伟大的工作。 – 2017-06-26 14:04:16

0

在迅速3.x中,我们可以使用它在UIWebview

@IBOutlet weak var webView : UIWebView! 
    class ViewController: UIViewController,UIWebViewDelegate { 

     override func viewDidLoad() { 
      super.viewDidLoad() 
      webView.delegate = self 
    } 
    func loadWebView() { 
      webView.loadHTMLString("<p>Hello, How are you doing?.</p>" , baseURL: nil) 
     } 
    func webViewDidFinishLoad(_ webView: UIWebView) { 
      webView.frame.size.height = 1 
      webView.frame.size = webView.sizeThatFits(.zero) 
    } 
    } 
用于显示脚本 loadHTMLString(_ string: String, baseURL: URL?) 功能

注: - 正如我在 webViewDidFinishLoad方法上面提到的,我们可以设置一个UIWebView的高度