使用不同的用户代理加载 iframe 内容

2022-01-20 00:00:00 popup browser html

是否可以使用不同的用户代理加载 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.

相关文章