I am trying to inject JS in a UIWebView. To some extent, everything worked like a charm:
In viewDidLoadI loaded the HTML button in the WebView:
NSString *loadedHTML = <input type='button' onclick='test();' value='test'/>;
[_webView loadHTMLString:loadedHTML baseURL:nil];
so that I can check if my JS function is working just by clicking a button. In webViewDidFinishLoad:webViewI introduced the JS function:
NSString *jsScript =
@"var test = function() {alert('not in class')};"
@"document.getElementsByTagName('head')[0].appendChild(test);";
[webView stringByEvaluatingJavaScriptFromString:jsScript];
This works great.
Now I need to create a similar function, but it should be inside the object. I tried:
HTML change, so the button calls the function of the object:
loadedHTML = <input type='button' onclick='myObject.test();' value='test'/>;
JS change, so it creates an object and a function in it:
jsScript =
@"var myObject = new function() {"
@"var test = function() {alert('not in class')};"
@"document.getElementsByTagName('head')[0].appendChild(myObject);";
@"}";
He does not do anything. I tried to create the object in three different ways , add myObject.testto the document - nothing helped. What am I doing wrong here?