如何将JQuery注入UIWebView中的现有页面? [英] How to inject JQuery into existing page within a UIWebView?

查看:132
本文介绍了如何将JQuery注入UIWebView中的现有页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JQuery注入我无法控制的页面的 UIWebView ,例如Google。当 UITextField 获得焦点时,我正在执行以下代码行:

I am trying to inject JQuery into a UIWebView of a page that I can't control, say Google, for example. When a UITextField gets focus, I am executing the following lines of code:

NSString* scriptInject = @"var headElement = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); 
    script.setAttribute('src','http://jquery.com/src/jquery-latest.js');
    script.setAttribute('type','text/javascript'); headElement.appendChild(script);";
    [myWebView stringByEvaluatingJavaScriptFromString:scriptInject];    
    [myWebView stringByEvaluatingJavaScriptFromString:@"$(document).ready(function() {$('body').css('background', '#FF0000');}"];

我正在执行后台更改以验证我能够运行JQuery脚本。我可以验证Objective-C方法正在调用,我甚至为新创建的< script> 标记的onload种植了一个 alert ,所以我知道它正在 UIWebView 中执行。如何正确地执行它我可以执行它?

I am executing the background change to validate that I am able to run a JQuery script. I can verify that the Objective-C method is being called, and I even planted an alert for the onload of the newly created <script> tag, so I know that it is being executed in the UIWebView. How do I inject it correctly that I can execute it?

编辑:

我在调用函数改变颜色后尝试了这个事件:

I have event tried this after calling the function to change the color:

[myWebView stringByEvaluatingJavaScriptFromString:@"alert($('body').css());"];

没有警报显示。

推荐答案

如果jQuery不在DOM中,你可以使用 stringByEvaluatingJavaScriptFromString:注入它。我我有类似的问题,我写了一篇关于它的博客文章: iOS中的HTML解析/屏幕抓取

If jQuery is not in the DOM already you can use stringByEvaluatingJavaScriptFromString: to inject it. I've had similar problem, I wrote a blog post about it: HTML parsing/screen scraping in iOS.

这篇关于如何将JQuery注入UIWebView中的现有页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆