javascript PhantomJS 和 iFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9941408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PhantomJS and iFrame
提问by babi4
I'm using phantomjs(1.5) and casperjsfor my functional tests.
我正在使用 phantomjs(1.5) 和casperjs进行功能测试。
casper = require('casper').create
loadImages: false
casper.start 'http://vk.com', ->
@fill 'form[name="login"]', { email: mail, pass: pass}, true
casper.thenOpen "http://vk.com/#{app}", ->
@echo "User at #{app}"
casper.then ->
@click "iframe['element']" #?! how I can do it?
casper.then ->
@wait 2000000, -> @echo "exit from room: #{num}"
casper.run()
So, I login to vk.com (social network in Russia), my app loaded with iframe.
所以,我登录到 vk.com(俄罗斯的社交网络),我的应用程序加载了 iframe。
How I can use elements in iFrame, for example click to a button?
如何使用 iFrame 中的元素,例如单击按钮?
回答by Pedro Vargas
The recent versions of PhantomJS allow us to use the --web-security=noflag for non respect the security policy.
PhantomJS 的最新版本允许我们使用--web-security=no标志来不遵守安全策略。
The next script (only PhantomJS) get the title of a link in the iframe, an iframe (adsense).
下一个脚本(仅 PhantomJS)获取 iframe 中链接的标题,一个 iframe (adsense)。
/*
Accessing an iframe (different domain) with PhantomJS
Example by deerme.org
*/
var page = require('webpage').create(), system = require('system'), t, address;
if (system.args.length === 1)
{
console.log('Usage: phantomfs iframe.js <some URL>');
phantom.exit();
}
t = Date.now();
address = system.args[1];
page.open(address, function (status)
{
if (status !== 'success')
{
console.log('FAIL to load the address');
}
else
{
t = (Date.now()) - t;
title = page.evaluate( function(){
return document.title;
});
linkTitle = page.evaluate( function(){
// The site containing jQuery?
if ( typeof(jQuery) == "undefined" )
{
// Force Load
page.injectJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
}
// first iframe #aswift_2
// second iframe #google_ads_frame3
return jQuery("#aswift_2").contents()
.find("body")
.find("#google_ads_frame3")
.contents()
.find("body")
.contents()
.find("a:last")
.attr("title");
});
console.log('Loading time: ' + t + ' msec');
console.log('Webpage title: ' + title);
console.log('Link title (iframe adsense): ' + linkTitle);
}
phantom.exit();
});
Remember, run with the parameter
请记住,使用参数运行
phantomjs --web-security=no iframe.js http://anysite.org
phantomjs --web-security=no iframe.js http://anysite.org
回答by Trevor Burnham
If your application is on a different domain than the one in the iframe, then your script can't interact with the iframe's contents. See: Can scripts in iframe interact with scripts in the main page
如果您的应用程序与 iframe 中的域位于不同的域中,则您的脚本无法与 iframe 的内容进行交互。请参阅:iframe 中的脚本能否与主页中的脚本交互