试图满足的业务需求:在 iframe 中加载现有页面,模拟 iphones 用户代理。这需要在客户端发生的原因是有 客户端脚本 检测用户代理并将一些类附加到 html 元素上。基于此,当 CSS 以基于 html 类的元素为目标时,站点的样式将发生根本性的变化。
所以它会变成或在我试图在这里解决的情况下等等。
在 chrome 中使用 window.open 工作(如本代码所示)。该网站以适当的移动样式呈现。
使用 iframe 有效,但仅限于 FF。
理想情况下,我希望在 Chrome 和 FF 中使用 iframe 版本。
有什么想法吗?
<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文档。 在 之后打开它,然后覆盖它的 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();
}
});
});
关于c# - 通过javascript设置iframe的用户代理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14248446/