2011-12-19 5 views
3

J'essaie d '"injecter" un fichier css local dans un fichier xhtml téléchargé.Injection d'un fichier css local dans UIWebView

Je trouve de nombreux exemples de la façon de le faire, mais ça ne marche pas pour moi ...

Voici mon code:

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{ 
    NSString *path = [[NSBundle mainBundle] bundlePath]; 
    NSString *cssPath = [path stringByAppendingPathComponent:@"test.css"]; 

    NSString *js = [NSString stringWithFormat:@"var cssNode = document.createElement('link');" 
       "cssNode.type = 'text/css';" 
       "cssNode.rel = 'stylesheet';" 
       "cssNode.href = '%@';", cssPath]; 
    js = [NSString stringWithFormat:@"%@document.getElementsByTagName('head')[0].appendChild(cssNode);", js]; 
    //m_webview is a member 
    [m_webView stringByEvaluatingJavaScriptFromString:js]; 
} 

ce que je fais mal ici?

Merci,

Répondre

7

J'ai également eu du mal à le faire.

J'essayais de charger un fichier HTML à partir d'un serveur et de changer le style en utilisant un fichier CSS local.

Au début, je

[webView loadRequest:reqObj]; 

Et quand il a frappé - (void)webViewDidFinishLoad:(UIWebView *)webView je tente de pousser le fichier CSS comme un enfant à la 'tête':

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{ 
NSString *path = [[NSBundle mainBundle] bundlePath]; 
NSString *cssPath = [path stringByAppendingPathComponent:@"style.css"]; 

NSString *js = [NSString stringWithFormat:@"var cssChild = document.createElement('link');" 
       "cssChild = 'text/css';" 
       "cssChild = 'stylesheet';" 
       "cssChild = '%@';", cssPath]; 
js = [NSString stringWithFormat:@"%@ document.getElementsByTagName('head')[0].appendChild(cssChild);", js]; 
[webView stringByEvaluatingJavaScriptFromString:js]; 
} 

Alors ... il n » ai pas travail t ...

puis j'ai essayé

NSString *path = [[NSBundle mainBundle] bundlePath]; 
NSURL *baseURL = [NSURL fileURLWithPath:path];  
[webView loadHTMLString:htmlString baseURL:baseURL]; 

(J'ai copié la chaîne HTML dans htmlString) puis, à l'intérieur - (void)webViewDidFinishLoad:(UIWebView *)webView j'ai injecté le CSS comme dans le code ci-dessus. Et ça a marché!

Mais ... mon fichier HTML est stocké dans un serveur distant et je n'avais pas la chaîne HTML, donc j'utilisé

NSString* myFile = [NSString stringWithFormat:@"http://blablabla.com/file.html"]; 
NSString* myFileURLString = [myFile stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 
NSData *myFileData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myFileURLString]]; 
NSString* myFileHtml = [[[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding] autorelease]; 

Pour obtenir le code HTML. Maintenant, j'ai le texte HTML brut dans 'myFileHtml'. J'utilise maintenant

NSString *path = [[NSBundle mainBundle] bundlePath]; 
NSURL *baseURL = [NSURL fileURLWithPath:path];  
[webView loadHTMLString:myFileHtml baseURL:baseURL]; 

et attraper la réponse dans « webViewDidFinishLoad », injectant mon fichier CSS dans et cela a fonctionné :)

Peut-être il y a une autre, plus élégante, la solution à ce problème, mais c'est ce que je suis venu avec ...

Espérons que cela a aidé.

+0

Merci! Cela a fonctionné. Je viens d'ajouter '[myFileData release];' – Gal

0

peut-être que cela devrait faire l'affaire? (Non testé dans Xcode):

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{ 

    NSString *path = [[NSBundle mainBundle] bundlePath]; 
    NSString *cssPath = [path stringByAppendingPathComponent:@"test.css"]; 

    NSString *js = [NSString stringWithFormat:@"var cssNode = document.createElement('link');" 
        "cssNode.type = 'text/css';" 
        "cssNode.rel = 'stylesheet';" 
        "cssNode.href = '%@';", cssPath]; 
    js = [NSString stringWithFormat:@"%@document.getElementsByTagName('head')[0].appendChild(cssNode);", js]; 


    NSString *k = [NSString stringWithFormat:@"var script = %@; %@", cssPath, js]; 

    //m_webview is a member 
    [m_webView stringByEvaluatingJavaScriptFromString:k]; 
} 
+0

merci, mais il semble toujours la même chose. Je me demande, comment puis-je savoir si 'stringByEvaluatingJavaScriptFromString' a fonctionné ou échoué? – Gal

2

cssNode.href = '% @'; », cssPath];

La ligne ci-dessus échoue parce qu'il tente de récupérer le fichier à partir du serveur Web utilisant quelque chose comme:

.

cssNode.href = 'fichier: //% @'; ", cssPath];

accède au système de fichiers local. Vous pouvez utiliser le mode développeur de Safari pour inspecter le simulateur de l'iPhone et voir si le fichier est trouvé et chargé.J'ai finalement fini par implémenter des feuilles de style en ligne au lieu de lier à la feuille de style. Voici le code qui fonctionne pour moi

NSError *error; 
NSString *css = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"stylesheet" ofType:@"css"] encoding:NSASCIIStringEncoding error:&error]; 
css = [css stringByReplacingOccurrencesOfString:@"\n" withString:@" "]; // js dom inject doesn't accept line breaks, so remove them 

NSString *js = [NSString stringWithFormat:@"var styleNode = document.createElement('style');" 
       "styleNode.type = 'text/css';" 
       "styleNode.innerHTML = ' %@ ';", css]; 
js = [NSString stringWithFormat:@"%@document.getElementsByTagName('head')[0].appendChild(styleNode);", js]; 

[_webView stringByEvaluatingJavaScriptFromString:js]; 
1

Je me suis heurté à cela en cherchant une réponse à la même question. Je charge une page HTML à partir d'un serveur Web dans un UIWebView. Le HTML a déjà beaucoup de CSS, approprié pour l'affichage sur le Web. Dans mon cas, je voulais afficher: aucun des divs non pertinents. Je ne voulais pas stocker le HTML localement, puis charger à partir du fichier, donc je suis venu avec une autre solution, conceptuellement similaire à d'autres ici, mais plus à mon goût. C'est Swift 3. Avoir cette course après le chargement de la page, mais avant qu'il ne s'affiche:

let css = "#someDiv {display:none;} #otherDiv {display:none;} .someClass {display:none;}" 
let js = "var sheet = document.createElement('style');sheet.innerHTML = \"\(css)\";document.body.appendChild(sheet);" 
webView.stringByEvaluatingJavaScript(from: js) 
Questions connexes