将参数从objective传递给javascript

时间:2013-06-10 11:49:49

标签: javascript objective-c

我想从objective-c向javascript发送一些NSString值。 这是代码:

Javascript.html

<!DOCTYPE html>
<html>
    <head>
        <title>Sample Page that Writes Out an HTML Addition Table</title>
        <script src=“doc.js”></script>
    </head>
    <body>
    </body>
</html>

doc.js

function call(str){
    document.write('<table border="1" cellspacing="1" cellpadding="5">')
    for(i = 0; i < 4; i++){
        document.write('<tr>')
        for (j = 0; j < 3; j++){
            document.write('<td>'+str+'<img src= '+str+'> </img></td>')
        }
        document.write('</tr>')
    }
    document.write('</table>')
}

.m文件

-(IBAction) show:(id) sender{

    NSString *htmlpath = [[NSBundle mainBundle] pathForResource:@"Javascript" ofType:@"html"];
    NSString *html =[NSString stringWithContentsOfFile:htmlpath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@",[[NSBundle mainBundle] bundlePath]] ];
    [[webView mainFrame] loadHTMLString:html baseURL:baseURl];

    NSString *jsTable=[NSString stringWithFormat:@"call('file:///Users/developer/Library/Billing/Barcodes/CO_BAT01_14.png')"];
    NSLog(@"jsTable = %@",jsTable);
    [webView stringByEvaluatingJavaScriptFromString:jsTable];
    [jsTable release];
}

我想从我的应用程序将图像路径发送到.js文件。 任何人都可以帮助我解决我的问题! 在此先感谢。

1 个答案:

答案 0 :(得分:1)

在执行javascript之前,您应该等待HTML加载。为WebView设置frameLoadDelegate并实现此方法:

- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
    NSString *jsTable=[NSString stringWithFormat:@"call('file:///Users/developer/Library/Billing/Barcodes/CO_BAT01_14.png')"];
    NSLog(@"jsTable = %@",jsTable);
    [sender stringByEvaluatingJavaScriptFromString:jsTable];
    [jsTable release];
}