iOS:在OC中調用JS指令碼:樣本一

來源:互聯網
上載者:User

標籤:

1.首先匯入JavaScriptCore.framework這個架構

2.建立webView、設定代理、請求手機端百度

#import "ViewController.h"#import <JavaScriptCore/JavaScriptCore.h>#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height@interface ViewController ()<UIWebViewDelegate>@property (strong,nonatomic)UIWebView *webView;@property (assign,nonatomic)BOOL isFirstLoadWeb;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        self.webView = [[UIWebView alloc]initWithFrame:self.view.bounds];    self.webView.scalesPageToFit = YES;    self.webView.backgroundColor = [UIColor clearColor];    self.webView.delegate = self;    [self.view addSubview:self.webView];    NSURL *URL = [NSURL URLWithString:@"http://m.baidu.com"];    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:URL];    [self.webView loadRequest:request];}

3.通過代理方法,在裡面調用自訂的JS指令碼

-(void)webViewDidFinishLoad:(UIWebView *)webView{        //程式會一直調用該方法,所以判斷若是第一次載入後使用我們自訂的js,此後不再調用JS,否則會出現網頁抖動現象    if (!_isFirstLoadWeb) {        _isFirstLoadWeb = YES;                //擷取當前頁面的url        NSString *url = [webView  stringByEvaluatingJavaScriptFromString:@"document.location.href"];        //擷取頁面的title        NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];                NSLog(@"%@----%@",url,title);                //給webView添加一個自訂的JavaScript        [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement(‘script‘);"            "script.type = ‘text/javascript‘;"            "script.text = \"function myFuncation(){"            "var field = document.getElementsByName(‘word‘)[0];"            "field.value = ‘夏先森的部落格園‘;"            "document.forms[0].submit();"         "}\";"         "document.getElementsByTagName(‘head‘)[0].appendChild(script);"];                //開始調用自訂的JavaScript        [webView stringByEvaluatingJavaScriptFromString:@"myFuncation();"];    }else{        return;    }}@end

示範如下:

2016-04-18 21:37:24.670 OC調用JS[7568:356964] https://m.baidu.com/----百度一下

  

 

iOS:在OC中調用JS指令碼:樣本一

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.