【问题标题】:How to call a Javascript method in iOS?如何在 iOS 中调用 Javascript 方法?
【发布时间】:2015-08-15 19:22:44
【问题描述】:

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/quiz-1.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<p class="question">1. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>          
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>            
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>            
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>       
</ul>        


<p class="question">2. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">Answer 1</label><br/>           
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">Answer 2</label><br/>            
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">Answer 3</label><br/>           
<input type="radio" name="q2" value="d" id="q2d"><label for="q2d">Answer 4</label><br/>       
</ul>        

<p class="question">3. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q3" value="a" id="q3a"><label for="q3a">Answer 1</label><br/>            
<input type="radio" name="q3" value="b" id="q3b"><label for="q3b">Answer 2</label><br/>            
<input type="radio" name="q3" value="c" id="q3c"><label for="q3c">Answer 3</label><br/>           
<input type="radio" name="q3" value="d" id="q3d"><label for="q3d">Answer 4</label><br/>       
</ul>        

<p class="question">4. What is the answer to this question?</p>        

<ul class="answers">           
<input type="radio" name="q4" value="a" id="q4a"><label for="q4a">Answer 1</label><br/>            
<input type="radio" name="q4" value="b" id="q4b"><label for="q4b">Answer 2</label><br/>            
<input type="radio" name="q4" value="c" id="q4c"><label for="q4c">Answer 3</label><br/>            
<input type="radio" name="q4" value="d" id="q4d"><label for="q4d">Answer 4</label><br/>        
</ul>        

<p class="question">5. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q5" value="a" id="q5a"><label for="q5a">Answer 1</label><br/>            
<input type="radio" name="q5" value="b" id="q5b"><label for="q5b">Answer 2</label><br/>            
<input type="radio" name="q5" value="c" id="q5c"><label for="q5c">Answer 3</label><br/>           
<input type="radio" name="q5" value="d" id="q5d"><label for="q5d">Answer 4</label><br/>        
</ul>        

<p class="question">6. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q6" value="a" id="q6a"><label for="q6a">Answer 1</label><br/>            
<input type="radio" name="q6" value="b" id="q6b"><label for="q6b">Answer 2</label><br/>            
<input type="radio" name="q6" value="c" id="q6c"><label for="q6c">Answer 3</label><br/>            
<input type="radio" name="q6" value="d" id="q6d"><label for="q6d">Answer 4</label><br/>        
</ul>       

<p class="question">7. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q7" value="a" id="q7a"><label for="q7a">Answer 1</label><br/>            
<input type="radio" name="q7" value="b" id="q7b"><label for="q7b">Answer 2</label><br/>            
<input type="radio" name="q7" value="c" id="q7c"><label for="q7c">Answer 3</label><br/>            
<input type="radio" name="q7" value="d" id="q7d"><label for="q7d">Answer 4</label><br/>        
</ul>        

<p class="question">8. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q8" value="a" id="q8a"><label for="q8a">Answer 1</label><br/>            
<input type="radio" name="q8" value="b" id="q8b"><label for="q8b">Answer 2</label><br/>            
<input type="radio" name="q8" value="c" id="q8c"><label for="q8c">Answer 3</label><br/>            
<input type="radio" name="q8" value="d" id="q8d"><label for="q8d">Answer 4</label><br/>       
</ul>        

<p class="question">9. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q9" value="a" id="q9a"><label for="q9a">Answer 1</label><br/>            
<input type="radio" name="q9" value="b" id="q9b"><label for="q9b">Answer 2</label><br/>            
<input type="radio" name="q9" value="c" id="q9c"><label for="q9c">Answer 3</label><br/>            
<input type="radio" name="q9" value="d" id="q9d"><label for="q9d">Answer 4</label><br/>        
</ul>        

<p class="question">10. What is the answer to this question?</p>        

<ul class="answers">           
<input type="radio" name="q10" value="a" id="q10a"><label for="q10a">Answer 1</label><br/>            
<input type="radio" name="q10" value="b" id="q10b"><label for="q10b">Answer 2</label><br/>            
<input type="radio" name="q10" value="c" id="q10c"><label for="q10c">Answer 3</label><br/>            
<input type="radio" name="q10" value="d" id="q10d"><label for="q10d">Answer 4</label><br/>        
</ul>        

<br/>
<div id="results">            
Show me the answers!       
</div>                

<div id="category1">            
<p>              
<strong>Question 1:</strong> The correct answer is the <strong>Answer 1</strong>.</p>        
</div>        

<div id="category2">            
<p>              
<strong>Question 2:</strong> The correct answer is <strong>Answer 2</strong>.</p>        
</div>        

<div id="category3">            
<p>                
<strong>Question 3:</strong> The correct answer is <strong>Answer 3</strong>.</p>        
</div>        

<div id="category4">            
<p>               
<strong>Question 4:</strong> The correct answer is <strong>Answer 4</strong>.</p>        
</div>        

<div id="category5">            
<p>                
<strong>Question 5:</strong> The correct answer is <strong>Answer 1</strong>.</p>        
</div>        

<div id="category6">            
<p>                
<strong>Question 6:</strong> The correct answer is <strong>Answer 2</strong>.</p>        
</div>        

<div id="category7">            
<p>                
<strong>Question 7:</strong> The correct answer is <strong>Answer 3</strong>.</p>        
</div>        

<div id="category8">            
<p>               
<strong>Question 8:</strong> The correct answer is <strong>Answer 4</strong>.</p>        
</div>        

<div id="category9">           
<p>               
<strong>Question 9:</strong> The correct answer is <strong>Answer 1</strong>.</p>        
</div>        

<div id="category10">            
<p>                
<strong>Question 10:</strong> The correct answer is <strong>Answer 2</strong>.</p>        
</div>        

<div id="category11">            
<p>                
You answered them all right!</p>        
</div>
</body>
</html>

我的 iOS 编码遇到了一个大问题。我的要求是我有一个 HTML 文件。该文件包含一些多项选择问答。我将该 html 文件加载到 UIWebView 中。当我单击那个答案按钮时,我必须检索在 webView 上单击了哪个按钮。

我必须从 html 文件中检索该方法。

这怎么可能?

它不是重复的 Q,我已经用谷歌搜索过了,无论我得到什么,它都不能满足我的要求。

我的代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"Untitled" ofType:@"html"];
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];
   [_webview loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
  }
  - (void)webViewDidFinishLoad:(UIWebView*)theWebView
  {
    NSString* returnValue =[theWebView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
    NSLog(@"returnValue = %@ ",returnValue);
  }
  - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
  {
     NSLog(@" didFailLoadWithError");
  }

但我的输出是:Sample_JS[2218:44719] returnValue =

请帮帮我....

【问题讨论】:

    标签: javascript html ios webview


    【解决方案1】:

    在您的代码中,这是事情发生的顺序:

    1. 您在viewDidload 中加载请求
    2. 你的webview完成加载。所以你得到了选择的值。但此时。你还没有选择任何东西。
    3. 当你选择一个项目时,你没有做任何事情告诉 iOS 你选择了一个

    所以,我建议使用WKWebview,使用 JS 代码很好。

    1. 在你的 js 代码中,添加一个按钮来提交。 然后在按钮动作函数中

      function submit () {
          var message = //here get all your selected items
          window.webkit.messageHandlers.observe.postMessage(message);
       }
      
    2. 在 ViewController 中,创建 WKUserContentController 来处理通知

      WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
      WKUserContentController *controller = [[WKUserContentController alloc]
                                         init];
      [controller addScriptMessageHandler:self name:@"observe"];
       configuration.userContentController = controller;
      _webView = [[WKWebView alloc] initWithFrame:self.view.frame
                                configuration:configuration];
      
    3. 在委托方法中,处理js事件

      -(void)userContentController:(WKUserContentController *)userContentController
        didReceiveScriptMessage:(WKScriptMessage *)message {
      //message.body
      }
      

    更新整个项目

    #import <WebKit/WebKit.h>
    @interface ViewController ()<WKScriptMessageHandler>
    
    @property (strong, nonatomic) WKWebView  * webview;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        NSString *path;
        NSBundle *thisBundle = [NSBundle mainBundle];
        path = [thisBundle pathForResource:@"Untitled" ofType:@"html"];
        NSURL *instructionsURL = [NSURL fileURLWithPath:path];
    
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
        WKUserContentController *controller = [[WKUserContentController alloc]
                                           init];
        [controller addScriptMessageHandler:self name:@"observe"];
        configuration.userContentController = controller;
        _webview = [[WKWebView alloc] initWithFrame:self.view.frame
                                  configuration:configuration];
        [_webview loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
        [self.view addSubview:self.webview];
    }
    
    -(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
        NSLog(@"%@",message.body);
    }
    

    还有html文件

    <html>
    <head>
    <script type="text/javascript">
    function getFirstSelect(){
        var rates = document.getElementsByName('q1');
        var rate_value;
        for(var i = 0; i < rates.length; i++){
            if(rates[i].checked){
                rate_value = rates[i].value;
                break;
            }
        }
        window.webkit.messageHandlers.observe.postMessage(rate_value);
    }
    </script>
    
    <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
    <p class="question">1. What is the answer to this question?</p>
    
    <ul class="answers">
    <input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>
    <input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>
    <input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>
    <input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>
    </ul>
    
    <div id="Submit">
         <button onclick="getFirstSelect()">Submit</button>
    </div>
    
    </body>
    </html>
    

    点击提交时

    这是一个测试项目,相信你可以自己解决

    【讨论】:

    • 我遵循您的代码,但我不明白什么是 WKWebview。你能分享一些代码吗?
    • joshuakehn.com/2014/10/29/…参考这个链接。是iOS 8的新特性
    • - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { 这个方法没有调用......
    • 你能告诉我什么是:[控制器 addScriptMessageHandler:self name:@"observe"]; .. 什么是观察....?
    • observe 是你用来发帖的名字window.webkit.messageHandlers.observe.postMessage
    【解决方案2】:

    我终于能够解决这个大问题了..

    首先为您的 WebView 设置委托方法。

     - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
     if ([[[request URL] absoluteString] hasPrefix:@"ios:"])
     {
        // Call the given selector
        [self performSelector:@selector(webToNativeCall)];
        return NO;
     }
     return YES;
    }
    
    - (void)webToNativeCall
    {
     NSString *returnvalue =  [self.webview stringByEvaluatingJavaScriptFromString:@"returnVal()"];
     NSLog(@"returnvalue == %@",returnvalue);
    }
    

    在 javascript 文件中:

    function getData ()
    {
       window.location  = 'ios:webToNativeCall';
    }
    function returnVal(){
      return values;
    }
    

    【讨论】:

      【解决方案3】:

      你必须在 JavaScript 中创建一个全局变量来存储答案的值。 你的函数 myFunction() 在 webview 加载后被调用,当用户被选中时,没有调用函数。所以你必须在一段时间内快速调用函数并检查它的值是什么

      【讨论】:

        【解决方案4】:

        请检查下面的代码,我已经在我的系统中测试过了。

        - (void)viewDidLoad
        {
            [super viewDidLoad];
        
            NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"html"];
            NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
            [self.webView loadHTMLString:htmlString baseURL:nil];
        
        }
        

        单击单选按钮后检查html结果的按钮操作方法 -

        - (IBAction)action:(id)sender {
        
            NSString* javaScriptString = @"document.querySelector('input[name=\"sex\"]:checked').value;";
            NSLog(@"%@",  [self.webView stringByEvaluatingJavaScriptFromString: javaScriptString]);
        }
        

        HTML 文件 -

        <!DOCTYPE html>
        <html>
            <body>
        
                <form action="">
                    <input type="radio" name="sex" value="male">Male<br>
                    <input type="radio" name="sex" value="female">Female
                </form>
        
            </body>
        </html>
        

        【讨论】:

        • 感谢您的快速回复。但我没有任何 myFunction() 方法。我只有那个 HTML 文件。在那个文件中没有 onclick 方法,你能解释一下如何制作吗?
        • 好的!如果您单击单选按钮,那么单选按钮状态是否更改为选中?或者您可以提供html以供参考
        • 是的,单选按钮将变为选中...我更新了我的问题。请检查。
        • 请检查上面的代码,我已经在我的系统中测试过
        猜你喜欢
        • 1970-01-01
        • 2013-04-22
        • 1970-01-01
        • 2011-06-19
        • 2011-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-31
        相关资源
        最近更新 更多