iOS loadHtmlString in UIWebView doesn't work with Javascript

和自甴很熟 提交于 2019-12-21 04:06:46

问题


I have a iOS app to load a html string which refer to external css file and javascript file in the same directory.

Here is my html file:

<html>
<head>
    <meta name="viewport" content= user-scalable="no", width="device-width" />
    <meta http-equiv="Content-Type" content="text/html"; charset="UTF-8"/> 
    <link rel="stylesheet" type="text/css" href="mystyle.css" />
    <script type="text/javascript" src="myjavascript.js"></script>
</head>

The css file works fine but it seems the js file never loaded. What could be the reason?

By the way I'm using loadHtmlString: BaseUrl method to load my html string.

Thanks


回答1:


This question is a bit old, but since it has not been answered, I would like to point out that if you would like your web view to load a javascript file residing in your bundle, the way to do it is:

[webView loadHTMLString:html
               baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

If you don't specify the baseURL there is no chance that the javascript file is loaded.




回答2:


By default, xcode will put new Javascript files in Compile Resources instead of Bundle Resources. Click on your project, then on your target. Under 'Build Phases' you may see the Javascript files under 'Compile Sources'. Drag them to down to 'Copy Bundle Resources'.




回答3:


like the others have said

  • use baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

  • copy Bundle Resources and not in Compile Resources.

thats it!



来源:https://stackoverflow.com/questions/11237229/ios-loadhtmlstring-in-uiwebview-doesnt-work-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!