2013-06-22 84 views

回答

4

是的,您需要创建一个自定义NSURLProtocol,如本帖子所示:https://stackoverflow.com/a/5573155/244160。根据示例,在canInitWithRequest:中进行适当的检查,然后按照正确的内容类型提供您的Javascript。

更新:

这里有一个快速打一枪换一个简单的实现:

@interface LocalJSURLProtocol : NSURLProtocol  
@end 

@implementation LocalJSURLProtocol 

+ (BOOL)canInitWithRequest:(NSURLRequest *)request 
{ 

    return [request.URL.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame && [request.URL.lastPathComponent hasSuffix:@"js"]); 
} 

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request 
{ 
    return request; 
} 

- (void)startLoading 
{ 
    NSURLRequest *request = self.request; 

    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL] 
                 MIMEType:@"text/javascript" 
              expectedContentLength:-1 
               textEncodingName:nil]; 

    NSString *localFilePath = [[NSBundle mainBundle] pathForResource:@"sample.js" ofType:nil]; 
    NSData *data = [NSData dataWithContentsOfFile:localFilePath]; 

    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; 
    [self.client URLProtocol:self didLoadData:data]; 
    [self.client URLProtocolDidFinishLoading:self]; 

} 

- (void)stopLoading 
{ 
} 

@end 

你开始加载之前这样注册[NSURLProtocol registerClass:[LocalJSURLProtocol class]];的协议。这将拦截UIWebView中的请求,并且您有机会为请求文件注入自己的Javascript代码。

+0

这很好。我使用'[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:jsFile]'获得localFilePath。我将'js'文件添加到'Copy Bundle resources',它们不会自动添加。谢谢! – McDermott

-1

(请参阅下面我的编辑 - 有可能与当地的资产和远程HTML文件的工作,通过使用自定义协议)

这是不可能使用本地的js文件(或任何本地文件)在互联网上的文件。这与您无法从常规桌面浏览器在网站上打开本地JavaScript文件的事实类似。

你可以做的是调用你的网站的页面,将响应的html保存为本地html文件(在你的文档文件夹中),并将js url更改为本地。该网址应该是相对的。 例如:

documents 
- myapp 
-- index.html 
-- scripts.js 

里面的index.html你可以改变JS SRC是:

<script src="scripts.js" /> 
  • 评论:
    1. 我认为你可以访问和编辑网页。
    2. 如果本地js文件没有下载,您可以做一个很好的回退。
:类似于jQuery的CDN回落到本地文件,我们只能通过测试的命名空间的存在做相反的事,做一个备用服务器的文件(jQuery是刚刚例如,它可以与任何的js文件来完成。
<script src="jquery-2.0.0.min.js"></script> 
<script> 
if (typeof jQuery == 'undefined') { 
    document.write(unescape("%3Cscript src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js' 

类型= '文/ JavaScript的' %3E%3C/SCRIPT%3E“));}

希望帮助

编辑

后审查这一post,你也许能够从远程HTML文件访问本地文件(在他的榜样,他正在与本地的HTML文件,但它可能会用遥控器上以及工作)