로컬 파일을 참조하는 javaScript와 함께 StringBavaScriptFromstring을 사용할 수 있습니까?

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

문제

StringByevaluatingJavaScriptFromString을 사용하여 로컬 파일 (이 경우 CSS 파일이지만 잠재적으로 JS 파일)을 참조하는 JavaScript를 실행하고 싶습니다 (문서 폴더에서) ...

 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';
도움이 되었습니까?

해결책

과거에 내가 한 일은 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]]

그리고 일부 문자열 교체 또는 그 밖의 것으로 페이지에 주입하십시오. 그래도 조금 해킹.

다른 팁

이렇게해야합니다.

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

이것이 문제를 해결하기를 바랍니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top