在我的selenium自动化测试中,我正在使用远程webdriver并尝试启动html文件,如下所示。 HTML页面打开正确,但在代码的最后部分,我试图点击一个调用javascript函数(ActionDeterminator())的提交按钮。当单击该按钮以调用js函数(ActionDeterminator())时,我在控制台中看到一个错误,我在底部提到了这个错误。
下面是html:
String butNowButton = "<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN>" +
"<HTML><HEAD>" +
"<META http-equiv='Content-Type' content='text/html'; charset='UTF-8'>" +
"<META content='MSHTML 6.00.2900.3157' name='GENERATOR'></HEAD>" +
"<BODY>" +
"<H1>Hello It's a testing page</H1>" +
"<HR>" +
"<P>Enter the following fields and press the button to initiate Transaction" +
"transaction</P>" +
"<FORM name=SSO action='' method='post'>" +
"<TABLE border='1'>" +
" <TBODY>" +
" <TR>" +
" <TD>Name(*): </TD>" +
" <TD><INPUT title='Name' value='Adam' name='Name'>" +
" </TD></TR>" +
" <TR>" +
" <TH colSpan='2'><INPUT id='btnSubmit' onclick='return ActionDeterminator();' type='submit' value='Go to Content catalog' name='btnSubmit'>" +
" </TH></TR></TBODY></TABLE>" +
" <INPUT type=hidden value='https://someUrl/' name='HOOK_URL'>" +
"</FORM>" +
"<SCRIPT type='text/javascript' name='JavaScript'>" +
"function ActionDeterminator()" +
"{" +
"document.SSO.action=document.SSO.URL.value+'/Buyer/Main/ad/somePath/DirectAction';" +
"alert('URL is ==>'+document.SSO.action);" +
"document.SSO.submit();" +
"}" +
"</SCRIPT>" +
"<HR>" +
"</BODY></HTML>";
//Below is the quick code to use above html and launch a page. This also //works fine, ( in the sense, html page is opened).
String htmlDiv = "var div=document.createElement('div');div.innerHTML=\"" + butNowButton + "\";arguments[0].appendChild(div);";
System.err.println("***" + htmlDiv);
//'dr' is basically remote webdriver.
WebElement element = dr.findElementsByTagName("BODY").get(0);
dr.executeScript(htmlDiv, element);
//below code tries to invoke function ActionDeterminator().
dr.executeScript("document.getElementById('btnSubmit').click();","");
在控制台中我看到以下错误:
data:,:1 Uncaught ReferenceError: ActionDeterminator is not defined
at HTMLInputElement.onclick (data:,:1)
at <anonymous>:248:70
at callFunction (<anonymous>:237:33)
at <anonymous>:247:23
at <anonymous>:248:3
onclick @ data:,:1
(anonymous) @ VM50:248
callFunction @ VM50:237
(anonymous) @ VM50:247
(anonymous) @ VM50:248
data:,:1 Not allowed to navigate top frame to data URL: data:,
答案 0 :(得分:0)
如果在DOM中使用onclick事件处理程序,则应将ActionDeterminator
函数定义放在<head>
或window.onload事件的回调中。
答案 1 :(得分:0)
我在浏览器devtool的控制台中尝试了你的代码,它报告了相同的错误,即使我尝试了JQuery.click()或addEventLister('click'),两者都不起作用。
似乎浏览器本身不支持以下行为: 在页面加载后,元素的事件脚本会动态添加到元素中。
所以这个问题与Selenium无关,浏览器本身不支持本地。
答案 2 :(得分:0)
最终得到了它。这里提供的解决方案都没有工作,因此我更改了html并使用eval()块调用了该函数。这对我有用。只需将其添加到其他人手中即可。帮助