简体   繁体   English

UIWebView:你能禁用Javascript吗?

[英]UIWebView: Can You Disable Javascript?

You can disable Javascript in both mobile Safari and Cocoa's WebView but I can see no means of doing so in UIWebView . 您可以在移动Safari和Cocoa的WebView中禁用Javascript,但我在UIWebView中看不到这样做。

Am I correct? 我对么?

I ask in relation to this question regarding obtaining the title of page displayed in an UIWebView using Javascript. 关于使用Javascript 获取UIWebView显示的页面标题,我想问一下这个问题。 I had worried that it would fail if Javascript was disabled but it appears the API does not allow the disabling of Javascript. 我担心如果Javascript被禁用会失败,但似乎API不允许禁用Javascript。

If Javascript cannot be deactivated UIWebView ,that renders my previous question moot. 如果Javascript无法停用UIWebView ,那使我以前的问题没有实际意义。

There is a way! 有一种方法! Using the Content Security Policy which is partially supported in iOS 5.1 and up, and a custom header: 使用iOS 5.1及更高版本部分支持的内容安全策略和自定义标头:

X-WebKit-CSP: script-src none;

You can tell the UIWebKit to not allow javascript on the page entirely. 你可以告诉UIWebKit完全不允许在页面上使用javascript。 (or selectively only allow script from a specific domain, more information in the spec . (或选择性只允许脚本从特定的域,在详细信息规范

To do this from a server you control, you'll have to modify the response headers for the page to include the X-WebKit-CSP header... To do it from pages that are local (plain text or HTML data on device), you'll have to define and register a custom NSURLProtocol for loading your page, and send the header in your crafted NSHTTPURLResponse: 要从您控制的服务器执行此操作,您必须修改页面的响应标头以包含X-WebKit-CSP标头...从本地页面(设备上的纯文本或HTML数据)执行此操作,您必须定义并注册自定义NSURLProtocol以加载您的页面,并在您制作的NSHTTPURLResponse中发送标题:

NSDictionary *headers = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"script-src none",@"X-WebKit-CSP",
                         @"text/html",@"Content-type",
                         encoding,@"Content-encoding",
                         nil];
NSHTTPURLResponse *urlResponse = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL
                                                         statusCode:200
                                                        HTTPVersion:@"1.1"
                                                       headerFields:headers];
[self.client URLProtocol:self didReceiveResponse:urlResponse cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];

There is no public API to disable Javascript. 没有公共API来禁用Javascript。 So it is fairly safe to assume that it won't be disabled. 因此,假设它不会被禁用是相当安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM