0

我目前正在运行以下代码来设置我的 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];

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

4

1 回答 1

3

This is the javascript that will accomplish what you want:

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);
}

For your use case:

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];
于 2014-09-19T01:17:54.990 回答