2011-04-20 61 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的高度