0

I need to access a javascript variable which is declared inside a try block in the script

var ErrorResponse = "";

in my iOS app. I don't have much idea about javascript thats why I am unable to find out the way to do it. I am using this:

NSString *jsString = @"var temp = ErrorResponse; return temp";
NSString *myFieldValue1 = [self.viewYTParser stringByEvaluatingJavaScriptFromString:jsString];

to retrieve the value but it returns an empty string.

2
  • var ErrorResopnse = ""; is empty. Set a value to it like: var ErrorResopnse = "Foo"; Commented Dec 26, 2013 at 7:54
  • it is empty when it is initialized. It gets set with a value later in the code Commented Dec 26, 2013 at 7:55

2 Answers 2

3

Here is the code that should do the magic:

NSString *errorResponse = [self.viewYTParser stringByEvaluatingJavaScriptFromString:@"ErrorResponse"];

Just execute this line each time you need to retrieve the up-to-date value of ErrorResponse.

You shouldn't use the return keyword.
If you want your JS to return any value from stringByEvaluatingJavaScriptFromString then it should be something that you would regularly write after the return keyword in regular JS function - without the return word itself.

Sign up to request clarification or add additional context in comments.

7 Comments

Are you sure that this variable has value at the moment you execute this line?
Yes. And just for checking I also initialized it var ErrorResopnse = "something"; but still didn't get anything
I figured out what the problem was. It was not accessible because it was declared locally. I declared it as a global variable and it worked. But now the trouble is that I am not supposed to make changes in the script and I will have to access the local variable. How can I do this?
Create a global variable and keep the local variable as it is. Assign value of local variable to global variable and then use stringByEvaluatingJavaScriptFromString
@san Hi, I could have done it but as I said in comment above that I am not supposed to change the script.
|
0
// simplified expression, no function needed
NSString *expr = @"document.getElementById('myDiv').offsetHeight / document.getElementById('myDiv').style.lineHeight";
// now pass it to the web view and parse the result
int lines = [[self.webView stringByEvaluatingJavaScriptFromString:expr] intValue];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.