我在我的項目中有一個NSString
和一個webView(Objective-C for iPhone),我在webView中調用了index.html
,並且在其中插入了我的腳本(javascript)。UIWebview中的NSString
如何將NSString作爲var傳遞給我的腳本,反之亦然?
這是一個example,但我不太瞭解它。
我在我的項目中有一個NSString
和一個webView(Objective-C for iPhone),我在webView中調用了index.html
,並且在其中插入了我的腳本(javascript)。UIWebview中的NSString
如何將NSString作爲var傳遞給我的腳本,反之亦然?
這是一個example,但我不太瞭解它。
發送字符串Web視圖:
[webView stringByEvaluatingJavaScriptFromString:@"YOUR_JS_CODE_GOES_HERE"];
發送字符串從網頁視圖對象 - C:你實現UIWebViewDelegate協議(.h文件內)
宣告:
@interface MyViewController : UIViewController <UIWebViewDelegate> {
// your class members
}
// declarations of your properties and methods
@end
在Objective-C(在.m文件中):
// right after creating the web view
webView.delegate = self;
在Objective-C(.m文件內)也:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *url = [[request URL] absoluteString];
static NSString *urlPrefix = @"myApp://";
if ([url hasPrefix:urlPrefix]) {
NSString *paramsString = [url substringFromIndex:[urlPrefix length]];
NSArray *paramsArray = [paramsString componentsSeparatedByString:@"&"];
int paramsAmount = [paramsArray count];
for (int i = 0; i < paramsAmount; i++) {
NSArray *keyValuePair = [[paramsArray objectAtIndex:i] componentsSeparatedByString:@"="];
NSString *key = [keyValuePair objectAtIndex:0];
NSString *value = nil;
if ([keyValuePair count] > 1) {
value = [keyValuePair objectAtIndex:1];
}
if (key && [key length] > 0) {
if (value && [value length] > 0) {
if ([key isEqualToString:@"param"]) {
// Use the index...
}
}
}
}
return NO;
}
else {
return YES;
}
}
內部JS:
location.href = 'myApp://param=10';
和其他方式呢? :-) – MJB 2012-05-05 18:34:12
當通過一個NSString成一個UIWebView(用作JavaScript字符串)你需要確保逃避換行符以及單/雙引號:
NSString *html = @"<div id='my-div'>Hello there</div>";
html = [html stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"];
html = [html stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
html = [html stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
html = [html stringByReplacingOccurrencesOfString:@"\r" withString:@""];
NSString *javaScript = [NSString stringWithFormat:@"injectSomeHtml('%@');", html];
[_webView stringByEvaluatingJavaScriptFromString:javaScript];
r反向過程很好地描述@邁克爾凱斯勒
我已經添加了UIWebView和UIWebViewDelegate標籤(而不是xcode和html) – 2010-09-18 17:13:53