试图满足的业务需求:在 iframe 中加载现有页面,模拟 iPhone 用户代理。这需要在客户端发生的原因是,有客户端脚本它检测用户代理并将一些类附加到 html 元素上。基于此,站点的样式将发生根本性的变化,因为 CSS 的目标元素是基于 html 类的。
因此,如果我试图在这里解决问题,则需要将其转变为 or 等。
在 chrome 中使用 window.open 可以工作(如这段代码所示)。该网站以正确的移动样式呈现。
使用 iframe 可以,但仅限于 FF。
理想情况下,我希望 iframe 版本能够在 Chrome 和 FF 中运行。
有什么想法吗?
<script type="text/javascript">
navigator.__defineGetter__('userAgent', function () {
return 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5';
});
var win = window.open('/home/get');
win.navigator.__defineGetter__('userAgent', function () {
return 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5';
});
win.location.href = '/home/get'; //required
$(function () {
var frame = $('<iframe width="320" height="480"></iframe>');
frame.hide();
$('#container').append(frame);
(frame[0].contentWindow || frame[0].contentDocument).navigator.__defineGetter__('userAgent', function () {
return 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5';
});
frame.attr('src', '/home/get');
});
frame.fadeIn();
});
</script>
搞清楚了,适用于 FF、Chrome 和 IE。我不确定 Safari,因为我没有安装它。其概要是发出ajax请求,获取html,然后打开iframes文档。AFTER打开它,然后重写它的 userAgent getter,然后编写从 ajax 调用收到的 html。
$(function () {
var frame = $('<iframe width="320" height="480"></iframe>');
frame.hide();
$('#container').append(frame);
var contentWindow = frame[0].contentWindow || frame[0].contentDocument;
var setUA = function() {
if (Object.defineProperty) {
Object.defineProperty(contentWindow.navigator, 'userAgent', {
configurable: true,
get: function () {
return 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5';
}
});
} else if (Object.prototype.__defineGetter__) {
contentWindow.navigator.__defineGetter__('userAgent', function () {
return 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5';
});
} else {
alert('browser not supported');
}
};
$.ajax({
cache: false,
url: '/home/get',
success: function (html) {
contentWindow.document.open();
setUA();
contentWindow.document.write(html);
contentWindow.document.close();
frame.fadeIn();
}
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)