Load iframe content with different user agent
Asked Answered
S

6

21

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

Shapeless answered 11/10, 2012 at 17:42 Comment(1)
I think you'd have to proxy the page with a server. If you use some simple PHP you could probably manage to send fake headers.Aquacade
H
10

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.

Heritage answered 27/2, 2015 at 13:26 Comment(8)
nice solution although I had to change document.querySelector to document.getElementByIdColumelliform
Is this supposed to work in Chrome? I cannot get it to set the iframe's userAgent. No errors are thrown though.Theadora
@Theadora it is not supposed to work with any modern browser with enhanced security features.Heritage
This is not working for me right now in Windows Google Chrome Version 78.0.3904.108 (Official Build) (64-bit)Askwith
@Askwith it is not supposed to work with any modern browser with enhanced security features.Heritage
I used user-agent instead of userAgent like Object.defineProperty(window.navigator, 'user-agent', userAgentProp); and it works.Marilumarilyn
@MahmonirBakhtiyari "it works" .... in what browsers did that fix it?Cyclopedia
@Cyclopedia I tested it on Chrome browser, but don't remember which version was it.Marilumarilyn
V
7

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?

Vocation answered 11/10, 2012 at 17:46 Comment(3)
how can I use this to load an iframe src with the required user agent ?? not sure how to startShapeless
Granted you're not fighting origin-only issues you could assign this to the iframe object.Vocation
Hey @Fluidbyte... Can you share an example?Sardonyx
R
6

You could create a proxy that makes requests with a different user agent, and then load the iframe content through the proxy.

Rockoon answered 11/10, 2012 at 17:45 Comment(2)
Sounds pretty clever, probably the only solution when hitting cross-origin issues. Can you give a link to a SO question that deals with this? I'm not finding the right keywords to get good search results... (ps: just remembered about cors-anywhere, will try something with it)Movement
@Movement I added capability to my personal little dev server (published as version 2.7.0) and got it to work as expected with the last code block documented in the proxy section here: github.com/billymoon/sir#proxyRockoon
P
1

From what I see, you have two solutions:

  • Most of the websites don't render per user agent, they just recognize the user agent and redirect the user to the mobile view, reachable under a different domain (http://m.youtube.com/, for instance) or some other URL segment. You just have to check their documentation, get their mobile URL and load it in the iframe.

  • The other solution is point the Iframe to your application, and then fetch the document from your backend. Then you can change the request user agent.

From HTML is impossible to influence the request headers. But you can do it with javascript.

Platyhelminth answered 11/10, 2012 at 17:49 Comment(0)
C
0

The following has a chance of working iff:

  • the requested website provides permissive CORS headers in the response e.g. Access-Control-Allow-Origin: * which enables loading over ajax
  • the browser supports changing User-Agent in XHR (apparently this is no longer forbidden by the spec)

const MOBILE_UA = 'Mozilla/5.0 (iPhone;...'  // copy from your dev tools
const YOUR_IFRAME_SRC_URL = 'https://example.com';

const iframe = document.createElement('iframe');

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    // might need some escaping of xhr.response here
    iframe.srcdoc = xhr.response;
    document.body.appendChild(iframe);
  }
};
xhr.open("GET", YOUR_IFRAME_SRC_URL);
xhr.setRequestHeader('User-Agent', MOBILE_UA);  // succeeds in FF anyhow
xhr.send();



Cyclopedia answered 18/1 at 10:19 Comment(0)
V
-3

I'm guessing one may only change the user agent information for the entire browser window or tab. By loading the iframes at different times, one could change the user agent between loads to get two different iframes on one page with different user agent related content. I tested this with a trivial example page:

<!DOCTYPE html> <html> <body>
<iframe src="http://whatsmyuseragent.com/" name="mobile" width="60%" height="400px"></iframe>
<a href="http://whatsmyuseragent.com/" target="mobile">Mobile Spoof</a>
<iframe src="http://whatsmyuseragent.com/" name="pc" width="60%" height="400px" ></iframe>
</body> </html>

After loading this page in Firefox 36.0.1, I used the User Agent Switcher extension https://addons.mozilla.org/en-US/firefox/addon/user-agent-switcher/ to select iPhone 3.0, and then clicked the "Mobile Spoof" link to reload that frame. At that point I saw the same page showing a different user agent in each iframe. I'm sure the page load or reload timing could be automated with the setTimeout() method, or perhaps via event handlers. I'm not sure how to automate the user agent switch. I tried the setUserAgent function suggested by Aero Windwalker, but could not get it to work in Firefox 36 or Chrome 41. I would also like to create a page that does this well.

Vlaminck answered 19/3, 2015 at 3:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.