无法将cssFile的javascript注入UIWebView

时间:2012-08-10 10:15:37

标签: javascript objective-c ios uiwebview

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"htmlScript" ofType:@"html"];
    // make a file: URL out of the path
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];
    [self.m_webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [m_webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"  
     "script.type = 'text/javascript';"  
     "script.text = \"function changeCSS(cssFile, cssLinkIndex) { " 
     "alert('test');"
     "var oldlink = document.getElementsByTagName('link').item(cssLinkIndex);"
     "var newlink = document.createElement('link');"
     "alert('test2');"
     "newlink.setAttribute('rel', 'stylesheet');"
     "newlink.setAttribute('type', 'text/css');"
     "newlink.setAttribute('href', cssFile);"     
     "alert('test3');"
     "}\";"  
     "document.getElementsByTagName('head')[0].appendChild(script);"
     "document.getElementsByTagName('head')[0].item(0).replaceChild(script,oldlink);"
    ]; 

    [m_webView stringByEvaluatingJavaScriptFromString:@"changeCSS('Zstyle.css', 0);"];
}

无法拨打document.getElementsByTagName('head').item(0).replaceChild(script.newlink, script.oldlink);

0 个答案:

没有答案