E 'possibile utilizzare stringByEvaluatingJavaScriptFromString con JavaScript che fa riferimento i file locali?

StackOverflow https://stackoverflow.com/questions/1893715

Domanda

Voglio usare stringByEvaluatingJavaScriptFromString di eseguire un javascript che fa riferimento file locali (in questo caso i file CSS, ma i file potenzialmente js troppo) che si trovano sul dispositivo (nella cartella Documenti immagino?) ...

 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];

Come potrei ottenere questo lavoro? Funziona benissimo se uso un file CSS esterno, come

the_css.href='http://www.website.com/the_css.css';
È stato utile?

Soluzione

Quello che ho fatto in passato è usato questo codice durante il caricamento del codice HTML

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];

[webView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8 " baseURL:baseURL];

Questa passerà la posizione fascio come URL di base che dovrebbe causare gli URL relativi per funzionare correttamente. Certo che non c'è bisogno di utilizzare questo metodo loadData esatto, ci sono vari sovraccarichi. Basta avere il baseUrl in là e si dovrebbe essere pronti per partire.

Se tutto questo non si può usare qualcosa come:

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

e iniettare che nella pagina con alcune sostituzioni di stringa o qualsiasi altra cosa. Bit hacky però.

Altri suggerimenti

Si dovrebbe fare in questo modo.

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];

Spero che questo risolverà il problema.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top