3

I'm working on traversing an iframe tree, but have run into a specific issue with PhantomJS.

I am using a locally hosted page with the most basic of iframe examples.

<div>
frame 0
</div>
<iframe name="1-1" width="500px;height: 500px;" src="frame-1-1.html"></iframe>

Here is the Javascript code I am running via PhantomJS.

page.open(url,function(status){

var test = page.evaluate(function(){
    var iframes = document.getElementsByTagName('iframe');
    var frames = document.getElementsByTagName('frame');

    if(iframes.length >0)
    {
        iframes.item(0).name = 'test1';
        return iframes.item(0).name;
    }
    else if(frames.length > 0)
    {
        frames.item(0).name = 'test2';
        return frames.item(0).name;
    }
    return "replaced nothing";

});

fs.write('test.txt', page.content, "w");

console.log("test: " + test);
page.switchToFrame(test);
var test2 = page.evaluate(function()
{
    return document.getElementsByName('test1')[0].name;
});
console.log(test2);
console.log("||||" + page.frameName);
 });

The test.txt sample output file contains what is expected. "1-1" is replaced with "test1" within the html code.

The variable test contains the value "test1" as expected

The variable test2 contains the value "test1" as expected

BUT, page.switchToFrame(test) does not go within the expected frame. If page.switchToFrame("1-1") is run here, the page switches, ignoring previous changes to the DOM.

In turn, with the current code, page.frameName contains no value, since the frame was not switched to the inner iframe.

Am I missing something?

EyeOfTheHawks
  • 576
  • 1
  • 5
  • 16

1 Answers1

0

I found a workaround that solves this problem.

Inside of:

if(iframes.length >0)
{
    iframes.item(0).name = 'test1';
    return iframes.item(0).name;
}

and

else if(frames.length > 0)
{
    frames.item(0).name = 'test2';
    return frames.item(0).name;
}

if this is added before the returns:

var outhtml = iframes.item(0).outerHTML;

iframes.item(0).outerHTML = outhtml;

It forces some sort of update within PhantomJS which sorts out the problems. page.frameName at the end has the correct value of "test1" and test2 variable contains the value of NULL as expected

EyeOfTheHawks
  • 576
  • 1
  • 5
  • 16
  • Issue discovered with this. The innerHTML of the iframe is lost according to Phantom, so will have to find a way to replace that again too.. which puts me back at square one on a different issue – EyeOfTheHawks May 27 '14 at 15:19