Javascript Executor not clicking input inside iframe - Selenium - javascript

I had a problem with Javascript executor for selenium when clicking a certain input inside an iframe. The problem happens only on chrome works fine on IE and FF, don't know why
here's the html file:
<iframe id="iframContainer" ng-src="app/docManagement/upload/iframe/iframe.html" src="app/docManagement/upload/iframe/iframe.html">
<!DOCTYPE html>
<html lang="en" dir="{{dir}}" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<script src="jquery-1.9.1.min.js" type="text/javascript">
<script src="uploader.js" type="text/javascript">
<style type="text/css">
</head>
<body class="upload-control">
<div id="drop" class="dragdrop_zone">
<input id="uploader" type="file" multiple="" name="file">
</div>
<script type="text/javascript">
</body>
</html>
</iframe>
and here's my code to click on the element using selenium executor:
int uploadArea = Driver.GetFirstFrameIndex();
Driver.Upload_File_Generic(FileUpload);
try
{
Thread.Sleep(2000);
Driver.SwitchToFrame(uploadArea);
Initiate_Driver.ClickJSElement(By.Id(AddREsources_IDs.UploadArea),"Uploader",Messages.ElementValidation.Mandatory);
}
catch
{
}
Initiate_Driver.GetOutofFrame();
public static void SwitchToFrame(int index)
{
try
{
driver.SwitchTo().Frame(index);
}
catch
{
Messages.NoSuchFrame(FrameName, validation);
}
}
public static void ClickJS(By by, string ElementName)
{
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
string _JSCommand = "";
if (by.ToString().Contains("Id"))
{
string ID = by.ToString().Replace("By.Id: ", string.Empty);
_JSCommand = "document.getElementById('" + ID + "').click();";
}
else if (by.ToString().Contains("Name"))
{
string Name = by.ToString().Replace("By.Name: ", string.Empty);
_JSCommand = "document.getElementByName('" + Name + "').click();";
}
executor.ExecuteScript(_JSCommand);
}
AGAIN : The proble happens only on chrome but it's working very fine on IE and FF.

Related

Extract a variable value in JavaScript code from HTML

I'm getting the HTML code of a webpage using this parsing library called Kanna. Basically the stripped down version looks like this.
<!DOCTYPE html>
<html lang="en" class="no-js not-logged-in client-root">
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
window._sharedData = {
// Some JSON
};
</script>
<script type="text/javascript">
// Javascript code
</script>
<script type="text/javascript">
// More Javascript code
</script>
</body>
</html>
There are multiple script tags within the body. I want to access the one with the variable named window._sharedData and extract it's value which is a JSON dictionary.
I tried with using regular expressions but it's returning nil. Maybe something's wrong with my pattern?
if let doc = try? HTML(url: mixURL, encoding: .utf8), let body = doc.body, let htmlText = body.text {
let range = NSRange(location: 0, length: htmlText.utf8.count)
let regex = try! NSRegularExpression(pattern: "/<script type=\"text/javascript\">window._sharedData = (.*)</script>/")
let s = regex.firstMatch(in: htmlText, options: [], range: range)
print(s)
}
Or is there a better way to do this?
Here it is:
import Foundation
import Kanna
let htmlString = "<!DOCTYPE html><html lang=\"en\" class=\"no-js not-logged-in client-root\"><head> <meta charset=\"utf-8\"></head><body> <script type=\"text/javascript\"> window._sharedData = { \"string\": \"Hello World\" }; </script> <script type=\"text/javascript\"> </script> <script type=\"text/javascript\"> </script></body></html>"
guard let doc = try? HTML(html: htmlString, encoding: .utf8) else { print("Build DOM error"); exit(0) }
let body = doc.xpath("//script")
.compactMap { $0.text }
.filter { $0.contains("window._sharedData") }
.map { $0.replacingOccurrences(of: " window._sharedData = ", with: "") }
.map { $0.dropLast(2) }
.first
print("body: ", body)
// body: Optional("{ \"string\": \"Hello World\" }")
After that you can check that body not nil and ready

why javascript doesnt run

I am learning JavaScript.
I've written this code, but it does not seem to run.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script language="javascript" type="text/javascript">
function nav(){
try{
var str="<table border=1>";
for (var n in navigator){
str+="<tr><td>" + n + "</td></tr>";
}
str+="</table>
return("jetzt wird das Ding aufgelistet: <br/>" + str);
}catch(e){return(e);}
}
function writeit(){
document.write(nav());
}
</script>
<title>for learning purpos</title>
</head>
<body>
<form>
<script>
document.write(nav());
</script>
<p>press the button to get the properties in navigator</p>
<input type="button" id="btnNavigator" value="get" onclick="writeit();"/>
</form>
</body>
</html>
You haven't closed one string.
str+="</table>";
Best practice is to look into the console from developer tab, inspect page. Also on that tab on the bottom, you can try javascript code or even jQuery if you have the library added.
Your code it's wrong at line 13 you have Invalid or unexpected token because you didn't close the string and at line 30 nav it's not defined.
You can use this code:
function navBuild(n)
{
var tblS = "<table>";
var tblE = "</table>";
var strTrTd = "";
for (i=1; i<=n; i++)
{
strTrTd = strTrTd + "<tr><td>" + i + "</td></tr>";
}
var strAll = tblS + strTrTd + tblE;
console.log(strAll);
document.getElementById("contentBox").innerHTML = strAll;
}
And in your HTML you could use:
<input type="button" id="btnNavigator" value="get" onclick="navBuild(5);"/>
<div id="contentBox"></div>

Calling C# COM Object from javascript fails

I'm trying to call a COM C# Object from javascript code and get an object that doesn't contain the COM object functions.
I created a setup project for the C# COM library. The library is signed for COM interop, and the setup project output is signed for COM register on the machine it deployed at.
I see that the TLB is properly exported.
C# Code:
using System;
using System.Runtime.InteropServices;
namespace YaronTestCOM
{
[Guid("BD145EEC-ACAC-4FDB-B766-0F15CE07990F")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IComEvents))]
public class YaronComObject : IComObject, IObjectSafety
{
[ComVisible(false)]
public delegate void YaronFirstEventHandler(string args);
public event YaronFirstEventHandler YaronFirstEvent;
public int YaronFirstComCommand(string arg)
{
if (YaronFirstEvent != null)
YaronFirstEvent(arg);
return (int)DateTime.Now.Ticks;
}
public void Dispose()
{
}
}
[Guid("A3576AA4-9DE0-422D-BAA3-3FFB862E8007")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[ComVisible(true)]
public interface IComObject
{
[DispId(0x10000001)]
int YaronFirstComCommand(string arg);
[DispId(0x10000002)]
void Dispose();
}
[Guid("B551EC8B-4D19-4781-938C-9E50E70D37CD")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComEvents
{
[DispId(0x00000001)]
void YaronFirstEvent(string args);
}
}
HTML+Javascrip Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<object id="publisher" name="publisher" classid="clsid:BD145EEC-ACAC-4FDB-B766-0F15CE07990F"></object>
<title>Sender Test</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var msgTxt = $("#msgTxt");
$("#btnSend").click(function () {
var msg = msgTxt.val();
//publisher.YaronFirstComCommand is undefined!!!
var result = publisher.YaronFirstComCommand(msg);
alert('The message ' + msg + 'has been sent and returned ' + result);
});
});
</script>
</head>
<body>
<div>
<input type='text' id='msgTxt' />
<input type='button' value='Send Message' id='btnSend' />
</div>
</body>
Any ideas?

Code works in chrome and firefox but fails in IE9

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
function abc()
{
ansArray = ['a'];
document.write('<input type = "button" value = "a">');
document.write('<input type = "button" value = "b">');
var myButton = document.getElementsByTagName("input");
myButton[0].onclick = function() {
if(ansArray[0] == 'a')
myButton[0].style.backgroundColor = "green";
else
myButton[0].style.backgroundColor = "red";
}
myButton[1].onclick = function() {
if(ansArray[0] == 'b')
myButton[1].style.backgroundColor = "green";
else
myButton[1].style.backgroundColor = "red";
}
}
</script>
</head>
<body onload="abc()">
</body>
</html>
This code segment is to change the colour of the two buttons on click event,works fine in chrome and firefox but the onclick functions does not work in IE9. Please help... Thanks in advance
Try calling the function like
(function abc(){
// code here
})();
Also use ; after each function expression, i.e. myButton[0].onclick = function() {...};.
Working here.

how to make html page detect enter key pressed?

I am using VSTS 2008 + C# + .Net 3.5 + IIS 7.0 + ASP.Net to develop a web application. The web application has an aspx page called default.aspx. And I want to implement the effect that when user press the enter key of keyboard, it is the same effect of press button "Action". Any ideas how to implement?
Here is the default.aspx file,
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<script type="text/javascript">
function requery() {
var query = location.search.substring(1);
var pairs = query.split("&");
var param1Value = document.getElementById("txtParam1").value;
url = "/Default.aspx?param1=" + param1Value;
for (var i = 0; i < pairs.length; ++i) {
var pair = pairs[i];
if ((pair.indexOf("param1") != 0) && (pair.length > 0)) {
url += "&" + pair;
}
}
location.href = url;
}
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtParam1" runat="server"></asp:TextBox>
<input type="button" value="Action" onclick="requery()" />
</div>
</form>
</body>
</html>
Here is the code behind file default.aspx.cs,
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtParam1.Text = Request.QueryString["param1"];
}
}
}
add an event handler to the document's keydown event. explanation in the comments.
function keydownHandler(e) {
if (e.keyCode == 13) { // 13 is the enter key
requery(); // call your function.
// alternately, give your button an id and used
// document.getElementById('myID').click();
// prevent the browser from doing whatever it normally
// does when you push the enter key.
// (not tested for this situation, may need tweaking)
if (e.preventDefault) {
e.preventDefault(); // FF,chrome
}
else {
return false; // IE
}
}
}
// register your handler method for the keydown event
if (document.addEventListener) {
document.addEventListener('keydown', keydownHandler, false);
}
else if (document.attachEvent) {
document.attachEvent('onkeydown', keydownHandler);
}
If you are browsing from Internet Explorer this is an annoying issue. Add a textbox with a style of display:none;visibility:hidden; The enter key will respond appropriately. This typically occurs on forms with one text input in IE. Add the hidden one as mentioned above under your first input field

Categories

Resources