Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load iframe content with different user agent

Tags:

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.

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 ??

like image 618
Aakash Chakravarthy Avatar asked Oct 11 '12 17:10

Aakash Chakravarthy


2 Answers

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

Then you need to target the iframe element:

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

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

like image 178
Aero Wang Avatar answered Oct 06 '22 08:10

Aero Wang


You can do it with JavaScript:

navigator.__defineGetter__('userAgent', function(){
    return 'foo' // customized user agent
});

navigator.userAgent; // 'foo'

However, this will only work with a select number of browsers.

See this question: Mocking a useragent in javascript?

like image 33
Fluidbyte Avatar answered Oct 06 '22 08:10

Fluidbyte