WKWebView - 更改视口?

时间:2014-07-22 21:52:01

标签: javascript ios uiwebview ios8 wkwebview

我目前正在运行以下代码来设置我的WKWebView的视口:

NSString* viewPortjs = [NSString stringWithFormat:@"document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%dpx;', false);", (int) webView.frame.size.width];
[webView evaluateJavaScript:viewPortjs completionHandler:nil];

我可以看到,如果代码找到选择器viewport,它会正确设置它,但是我想添加将此行添加到DOM的能力(如果它不存在)。对于Javascript,我是一个菜鸟,所以我不知道如果不存在该选择器并添加它,如何更改此代码来处理该情况。谁能帮我吗?谢谢!

1 个答案:

答案 0 :(得分:3)

这是可以实现您想要的javascript:

var myCustomViewport = 'width=320px';
var viewportElement = document.querySelector('meta[name=viewport]');
if (viewportElement) {
        viewportElement.content = myCustomViewport;
} else {
    viewportElement = document.createElement('meta');
    viewportElement.name = 'viewport';
    viewportElement.content = myCustomViewport;
    document.getElementsByTagName('head')[0].appendChild(viewportElement);
}

对于您的用例:

NSString* viewPortjs = [NSString stringWithFormat:@"var myCustomViewport = 'width=%dpx'; var viewportElement = document.querySelector('meta[name=viewport]');if (viewportElement) {viewportElement.content = myCustomViewport;} else {viewportElement = document.createElement('meta'); viewportElement.name = 'viewport'; viewportElement.content = myCustomViewport; document.getElementsByTagName('head')[0].appendChild(viewportElement);}", (int) webView.frame.size.width];