简体   繁体   中英

Download files on a website with Javascript using iOS

I'm trying to download a file programmly on this site , and I found that when you click the highlighted download button("下载"), it runs a Javascript: document.getElementById('downLoad').action='/download.php?fileid=11024011';downishare('0');

On my Mac, it runs fine and downloads the file when I run it on Safari. But when I use

[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('downLoad').action='/download.php?fileid=11024011'"]];

It doesn't return anything.

Does anyone know why and how can I get the download URL?

Thanks.

Well... the download url is this: http://ishare.iask.sina.com.cn/download.php?fileid=11024011

You can check it also with the 'Network' tab in chrome or firebug in firefox. BUT... when you try to access it directly, it redirects you. There might be some server side validation of the request, like the referrer url or something.

Have you tried implementing the webView delegate method shouldStartLoadWithRequest to parse through links?


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
if ([[[request URL] absoluteString] hasPrefix:@"http://ishare.iask.sina.com.cn/download.php?fileid="])
//I believe this would download everything that has a link prefix of "http://ishare.iask.sina.com.cn/download.php?fileid="
//So you should create some sort of checker to make sure it only downloads the file they select
        // Determile cache file path
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0],@"index.html"];   
        // Download and write to file
        NSURL *url = [NSURL URLWithString:[[request URL] absoluteString]];
        NSData *urlData = [NSData dataWithContentsOfURL:url];
        [urlData writeToFile:filePath atomically:YES];

        // Load file in UIWebView
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];

        return NO;
    }
    else {
        return YES;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM