Insert IOS JS class object into WebView

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?

+4
2

, JS:

var myObject = {
   test: function() {alert('in class!')}
}

myObject.test().

+4

, :

NSString *jsScript =
@"var script = document.createElement('script');"
@"    script.type = 'text/javascript';"
@"    script.text = '"
@"        var myObject = (function() {"
@"            return {"
@"                test: function() {"
@"                    alert(\"foo\");"
@"                }"
@"            }"
@"        })();"
@"';"
@"document.getElementsByTagName('head')[0].appendChild(script);";

NSString *result = [self.webMain stringByEvaluatingJavaScriptFromString:jsScript];

( ) script DOM. JS, , .

, , , Javascript . , Javascript , , , Objective-C.

+1

Source: https://habr.com/ru/post/1536635/


All Articles