views:

383

answers:

1

So I would like to run the following Javascript on an open webpage in a UIWebView:

- (IBAction)pushDownoad {
    [webView stringByEvaluatingJavaScriptFromString:
     var myWin=window.open("","myWin","width=800,height=600,scrollbars,resizable,menubar");
     var myStr=document.documentElement.innerHTML.toLowerCase();
     myStr=myStr.replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\r\n/g,"<br>");
     var a=myStr.lastIndexOf("embed src=")+11; 
     var b=myStr.lastIndexOf("ec_rate");
     myStr=myStr.substring(a,b);     
     myStr='<a href="'+myStr+'">Get Video</a>';
     myWin.document.open();
     myWin.document.write(myStr);
     myWin.document.close();]
}

The whole point in this Javascript is to look for the text between two phrases and pull out that text from the source code. If this script is not usable how would i go about doing this so that the Javascript looks for text between two specific phrases(which will be a link) and then opens that link in the current UIWebView.

Thank you so much to everyone.

A: 

Okay, first off, you don't need to open a window and write to it (and it probably won't work anyway, window.open in UIWebViews used to fail, even though it worked in mobil safari). You just need to return the value, it will get marshaled into Objective C by itself. So your JS should look something like:

 var myStr=document.documentElement.innerHTML.toLowerCase();
 myStr=myStr.replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\r\n/g,"<br>");
 var a=myStr.lastIndexOf("embed src=")+11; 
 var b=myStr.lastIndexOf("ec_rate");
 myStr=myStr.substring(a,b);        
 myStr='<a href="'+myStr+'">Get Video</a>';

 //last statement will be returned
 myStr;

Assuming the above code is valid JS that returns what you want when you test it something like FireBug, you can use it with stringByEvaluatingJavaScriptFromString: to get that value in your app. You cannot just cut and past it in though, because you need to pass in an NSString. That means you either need to escape it, or preferably include it in a separate file in your resources that you just load in. For instance:

- (IBAction) pushDownoad {
  NSError *error = nil;
  NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:@"stringFinder" ofType:@"js"];
  NSString *jsCode = [NSString stringWithContentsOfFile:jsFilePath encoding:NSUTF8StringEncoding error:&error];
  NSLog(@"link code: %@", [webView stringByEvaluatingJavaScriptFromString:jsCode]);
}

Obviously you should check the error, and that assume you put the JS code into a file named stringFinder.js in your app's resources. At this point you have the link and you can do what you want with it including creating a new view to display it.

Louis Gerbarg