使用不同的用户代理加载 iframe 内容 [英] Load iframe content with different user agent

查看:29
本文介绍了使用不同的用户代理加载 iframe 内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用不同的用户代理加载 iframe ?为 iframe 使用移动用户代理将有助于我的应用将移动网站显示为悬停弹出窗口.

Is it possible to load an iframe with different user agent ?? Using a mobile user agent for an iframe will help my app to show mobile sites as hover popup.

例如,只有当用户代理来自移动端时,Google 才会显示移动搜索结果页面.

For example, Google shows the mobile search results page only if the user agent is from a mobile one.

是否有任何替代解决方案,或者这个想法是否涉及任何安全风险??

Is there any alternate solutions or is there any security risks involved in this idea ??

推荐答案

首先,你必须创建一个函数来改变用户代理字符串:

First of all, you must create a function to change the user agent string:

function setUserAgent(window, userAgent) {
  if (window.navigator.userAgent != userAgent) {
    var userAgentProp = {
      get: function() {
        return userAgent;
      }
    };
    try {
      Object.defineProperty(window.navigator, 'userAgent', userAgentProp);
    } catch (e) {
      window.navigator = Object.create(navigator, {
        userAgent: userAgentProp
      });
    }
  }
}

那么你需要定位iframe元素:

Then you need to target the iframe element:

setUserAgent(
    document.querySelector('iframe').contentWindow, 
    'Aakash Chakravarthy Mobile Agent'
);

您还可以为 iframe 设置一个 ID,并以该 ID 而非页面上的所有 iframe 元素为目标.

You may also set an ID to the iframe and target the ID instead of all iframe elements on the page.

这篇关于使用不同的用户代理加载 iframe 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆