【问题标题】:Is it possible to use stringByEvaluatingJavaScriptFromString with Javascript which references local files?是否可以将 stringByEvaluatingJavaScriptFromString 与引用本地文件的 Javascript 一起使用?
【发布时间】:2010-12-26 00:12:34
【问题描述】:

我想使用 stringByEvaluatingJavaScriptFromString 来运行一个 javascript,它引用设备上的本地文件(在本例中是 css 文件,但也可能是 js 文件)(我猜是在 Documents 文件夹中?)...

 NSString *theJS = [[NSString alloc]
 initWithString:@"javascript:(function()
{the_css.rel='stylesheet';
the_css.href='the_css.css';
the_css.type='text/css';
the_css.media='screen';}
)();"];

[webView stringByEvaluatingJavaScriptFromString:theJS];

我怎样才能让它发挥作用?如果我使用外部 css 文件,它可以正常工作,例如

the_css.href='http://www.website.com/the_css.css';

【问题讨论】:

    标签: javascript iphone uiwebview stringbyevaluatingjavascr


    【解决方案1】:

    你应该这样做。

    NSString *cssPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"the_css.css"];
    NSURL *baseURL = [NSURL fileURLWithPath:cssPath];
    
    
     NSString *theJS = [[NSString alloc]
     initWithFormat:@"javascript:(function()
    {the_css.rel='stylesheet';
    the_css.href='%@';
    the_css.type='text/css';
    the_css.media='screen';}
    )();",baseURL];
    [cssPath release];
    
    [webView stringByEvaluatingJavaScriptFromString:theJS];
    

    希望这能解决问题。

    【讨论】:

      【解决方案2】:

      我过去所做的是在加载 HTML 时使用此代码

      NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
      NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];
      
      [webView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8 " baseURL:baseURL];
      

      这会将捆绑包位置作为基本 url 传递,这将使您的相对 url 正常工作。当然你不必使用这个确切的loadData 方法,有各种重载。只需在其中输入baseUrl 就可以了。

      如果一切都失败了,你可以使用类似的东西:

      NSString *path = [[NSBundle mainBundle] pathForResource:@"file.css" ofType:nil]]
      

      并通过一些字符串替换或其他方式将其注入页面。不过有点hacky。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多