Wednesday, April 13, 2016

JSON parse error when switching to Google safeframe ads

Leave a Comment

I'm trying to switch through all the iframes in the DOM:

var frames = driver.FindElements(By.TagName("iframe"));     foreach (var frame in frames)   {      driver.SwitchTo().Frame(frame);     //Do stuff then switch back to default content } 

Some Google ad safeframes throw this exception when switching:

"JSON Parse error: Unterminated string"

I expected Selenium to read the content as HTML rather than JSON when switching to a frame.

The Google ad safeframe I am trying to switch to:

<iframe name="1-0-2;63563;<!doctype html><html><head><style><!--a:link { color: #000000 }a:visited { color: #000000 }a:hover { color: #000000 }a:active { color: #000000 }  --></style><script><!--(function(){var b=this;var f=String.prototype.trim?function(a){return a.trim()}:function(a){return a.replace(/^[\s\xa0]+|[\s\xa0]+$/g,&quot;&quot;)},m=function(a,c){return a<c?-1:a>c?1:0};var n;a:{var p=b.navigator;if(p){var q=p.userAgent;if(q){n=q;break a}}n=&quot;&quot;};var r=-1!=n.indexOf(&quot;Opera&quot;)||-1!=n.indexOf(&quot;OPR&quot;),t=-1!=n.indexOf(&quot;Trident&quot;)||-1!=n.indexOf(&quot;MSIE&quot;),u=-1!=n.indexOf(&quot;Edge&quot;),v=-1!=n.indexOf(&quot;Gecko&quot;)&amp;&amp;!(-1!=n.toLowerCase().indexOf(&quot;webkit&quot;)&amp;&amp;-1==n.indexOf(&quot;Edge&quot;))&amp;&amp;! 

The iFrame HTML is cut short as it's over 60,000 chars as the name attribute contains the iframes DOM.

Anyone know how I can get Selenium to switch to these google ad safeframes?

1 Answers

Answers 1

I've been able to reproduce the problem on the http://express.co.uk/ website - from time to time, there is a safeframe added to the DOM. From what I understand, the problem is that when you try to switch to a safeframe iframe (it has data-is-safeframe attribute set to true) using the frame IWebElement instance or it's id or name, PhantomJS responds with a JSON parse error. This should be reported at the PhantomJS issue tracker, as it is not related to a particular selenium language bindings (I've used the latest Python/Selenium - same error is thrown).

Workarounds:

  • use frame index to switch to the frame, worked for me (the complete Python code is in this gist). For example, here is how you can switch to the very first frame in C# (zero-based index):

    driver.SwitchTo().Frame(0); 
  • switch to Firefox or Chrome (you can run them in "headless" mode also)
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment