How to access Javascript array using COM with Autohotkey - javascript

I've been using Autohotkey for a while to access some elements on a webpage, I can do so just fine using: wb.document.elements[x].forms[x].value and assigning this to a value. I apologize but my knowledge of Javascript is very limited.
Recently I looked at the code for the page and noticed the following:
<script type="text/javascript" defer="defer">
form = new ActiveForm('EditingServiceInformationforSOMEGUY','Editing Service Information for SOME GUY');
data = {};
data.header = ["addressid", "contactid", "address1", "address2", "city", "state", "zip"];
data.body = [["275101010", "254101010", "1001 Maudlin", "Apt. 1774", "Beverly Hills", "CA", "90210"]];
I have been unsuccessfully trying to access the data.body portion of this through AHK. If I type in the address bar while viewing the page:
javascript: alert(data.body[0])
I get a messagebox with the data.body values comma separated.
I can't seem to replicate this through Autohotkey. I've tried a lot of different syntax but I'm missing something here. I'd like to get a msgbox with the same values that I'm seeing in the Javascript Alert, and then further manipulate them from there.
I've tried many different combinations in my script to show data.body as the list of comma separated variables, but can't seem to get it to fire correctly.
My current AHK code is below, the line that attempts to assign tempvar is the one I can't get right.
Settitlematchmode, 2
WinGetTitle, Webstring, Title of the page
wb := IEGet(Webstring)
tempvar := wb.document(data.header[0])
msgbox % tempvar . "|" . Isobject(tempvar)
IEGet(Name:="") {
IfEqual, Name,, WinGetTitle, Name, ahk_class IEFrame
Name := ( Name="New Tab - Windows Internet Explorer" ) ? "about:Tabs"
: RegExReplace( Name, " - (Windows|Microsoft) Internet Explorer" )
For wb in ComObjCreate( "Shell.Application" ).Windows
If ( wb.LocationName = Name ) && InStr( wb.FullName, "iexplore.exe" )
Return wb
}

#vasili111 was on the right track. Try this:
Settitlematchmode, 2
WinGetTitle, Webstring, Title of the page
wb := IEGet(Webstring)
IID := "{332C4427-26CB-11D0-B483-00C04FD90119}" ; IID_IHTMLWindow2
window := ComObj(9,ComObjQuery(wb,IID,IID),1)
tempvar := window.data.header.0
; or use
;tempvar := window.eval("data.header[0]")
msgbox % tempvar . "|" . Isobject(tempvar)
IEGet(Name:="") {
IfEqual, Name,, WinGetTitle, Name, ahk_class IEFrame
Name := ( Name="New Tab - Windows Internet Explorer" ) ? "about:Tabs"
: RegExReplace( Name, " - (Windows|Microsoft) Internet Explorer" )
For wb in ComObjCreate( "Shell.Application" ).Windows
If ( wb.LocationName = Name ) && InStr( wb.FullName, "iexplore.exe" )
Return wb
}

Related

Cannot show the new line in label

Hi I have a code using vb.net. I need to get the text in the textbox as a parameter for calling javascript function which set the text in the label on the parent page. I replace the new line with <br/>. But it still show the <br/>on the label. Would someone tell me what to solve it. Thanks in advance.
The text in the textbox:
test [ \ ^ $ . | ? * + ( )'
new line
The text shows in the parent label:
test [ ^ $ . | ? * + ( )'<br/>new line
There is my code int vb.net
Dim script as string=""
Dim strText As String = txtNote.Text.Trim.Replace("'", "\'")
strText = strText.Replace(Environment.NewLine, "<br/>")
script = "window.parent.showNote('" & Server.HtmlEncode(strText) & "');"
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.[GetType](), "EditNote", script, True)
There is javascript:
function showNote(txt){
$('#lbl').html(txt);
}
I changed the code and work:
Dim script as string=""
Dim strText As String = txtNote.Text.Trim.Replace("'", "\'")
strText A=Server.HtmlEncode(strText)
strText = strText.Replace(Environment.NewLine, "<br/>")
script = "window.parent.showNote('" & strText & "');"
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.[GetType](), "EditNote", script, True)

detecting multiple html tags with javascript and regex

I am building a chrome extension which would read the current page and detect specific html/xml tags out of it :
For example if my current page contains the following tags or data :
some random text here and there
<investmentAccount acctType="individual" uniqueId="1629529524">
<accountName>state bank of america</accountName>
<accountHolder>rahul raina</accountHolder>
<balance balType="totalBalance">
<curAmt curCode="USD">516545.84</curAmt>
</balance>
<asOf localFormat="MMM dd, yyyy">2013-08-31T00:00:00</asOf>
<holdingList>
<holding holdingType="mutualFund" uniqueId="-2044388005">
<description>Active Global Equities</description>
<value curCode="USD">159436.01</value>
</holding>
<holding holdingType="mutualFund" uniqueId="-556870249">
<description>Passive Non-US Equities</description>
<value curCode="USD">72469.76</value>
</holding>
</holdingList>
<transactionList/>
</investmentAccount>
</site>
some data 123
<site name="McKinsey401k">
<investmentAccount acctType="individual" uniqueId="1629529524">
<accountName>rahuk</accountName>
<accountHolder>rahuk</accountHolder>
<balance balType="totalBalance">
<curAmt curCode="USD">516545.84</curAmt>
</balance>
<asOf localFormat="MMM dd, yyyy">2013-08-31T00:00:00</asOf>
<holdingList>
<holding holdingType="mutualFund" uniqueId="1285447255">
<description>Special Sits. Aggr. Long-Term</description>
<value curCode="USD">101944.69</value>
</holding>
<holding holdingType="mutualFund" uniqueId="1721876694">
<description>Special Situations Moderate $</description>
<value curCode="USD">49444.98</value>
</holding>
</holdingList>
<transactionList/>
</investmentAccount>
</site>
So I need to identify say tag and print the text between the starting and ending tag i.e : "State bank of america" and "rahukk"
So this is what I have done till now:
function countString(document_r,a,b) {
var test = document_r.body;
var text = typeof test.textContent == 'string'? test.textContent : test.innerText;
var testRE = text.match(a+"(.*)"+b);
return testRE[1];
}
chrome.extension.sendMessage({
action: "getSource",
source: "XML DETAILS>>>>>"+"\nAccount name is: " +countString(document,'<accountName>','</accountName>')
});
But this only prints the innertext of only the first tag it encounters in the page i.e "State bank of america".
What if I want to print only "rahukk" which is the innertext of last tag in the page or both.
How do I print the innertext of last tag it encounters in the page or how does it print all the tags ?
Thanks in advance.
EDIT : The document above itself is an HTML page i have just put the contents of the page
UPDATE : So I did some here and there from the suggestions below and the best I could reach by this code :
function countString(document_r) {
var test = document_r.body;
var text = test.innerText;
var tag = "accountName";
var regex = "<" + tag + ">(.*?)<\/" + tag + ">";
var regexg = new RegExp(regex,"g");
var testRE = text.match(regexg);
return testRE;
}
chrome.extension.sendMessage({
action: "getSource",
source: "XML DETAILS>>>>>"+"\nAccount name is: " +countString(document)
});
But this gave me :
XML DETAILS>>>>> Retirement Program (Profit-Sharing
Retirement Plan (PSRP) and Money Purchase Pension Plan
(MPPP)),Retirement Program (Profit-Sharing
Retirement Plan (PSRP) and Money Purchase Pension Plan
(MPPP)),Retirement Program (Profit-Sharing
Retirement Plan (PSRP) and Money Purchase Pension Plan
(MPPP))
This again because the same XML was present in the page 3 times and What I want is that regex to match only from the last XML and I don't want the tag names too.
So my desired output would be:
XML DETAILS>>>>> Retirement Program (Profit-Sharing
Retirement Plan (PSRP) and Money Purchase Pension Plan
(MPPP))
you match method is not global.
var regex = new RegExp(a+"(.*)"+b, "g");
text.match(regex);
If the full XML string is valid, you can parse it into an XML document using the DOMParser.parseFromString method:
var xmlString = '<root>[Valid XML string]</root>';
var parser = new DOMParser();
var doc = parser.parseFromString(xmlString, 'text/xml');
Then you can get a list of tags with a specified name directly:
var found = doc.getElementsByTagName('tagName');
Here's a jsFiddle example using the XML you provided, with two minor tweaks—I had to add a root element and an opening tag for the first site.
Regex pattern like this: <accountName>(.*?)<\/accountName>
var tag = "accountName";
var regex = "<" + tag + ">(.*?)<\/" + tag + ">";
var testRE = text.match(regex);
=> testRE contains all your matches, in case of tag=accountName it contains "state bank of america" and "rahukk"
UPDATE
According to this page to receive all matches, instead of only the first one, you smust add a "g" flag to the match pattern.
"g: The global search flag makes the RegExp search for a pattern
throughout the string, creating an array of all occurrences it can
find matching the given pattern." found here
Hope this helps you!
You don't need regular expressions for your task (besides, read RegEx match open tags except XHTML self-contained tags for why it's not a good idea!). You can do this completely via javascript:
var tag = "section";
var targets = document.getElementsByTagName(tag);
for (var i = targets.length; i > 0; i--) {
console.log(targets[i].innerText);
}

Calling javascript from content page not working

My app consists of a Masterpage with content pages. The Masterpage contains javascript functions to manipulate a treeview by dynamically selecting and expanding nodes. In one instance I am trying to call the javascript function on the Masterpage through code-behind on a content page but the javascript never gets called. I placed break points in the javascript but they never get hit.
What needs to happen is that after the projects are deleted, the content page reloads and at the same time I need the javascript function to be called.
NOTE: the javascript does work as dynamically built links throughout the system do hit the breakpoints and the function runs.
Here is the code-behind method that I am making the call to the javascript from:
Protected Overrides Sub OnDelete(ByVal SelectedItems As System.Collections.Specialized.NameValueCollection)
For i As Integer = 0 To SelectedItems.AllKeys.GetLength(0) - 1
Dim strProjectId As String = SelectedItems.AllKeys(i)
Dim objProject As New BSProject(strProjectId)
BSProject.Delete(Val(strProjectId), Page)
' log action
BSActivity.Log(Page.User.SiteUser.intID, "Project Delete", _
"Project """ & objProject.strProjectName & """ of Organization """ & _
Projects.objOrganization.strName & """ was deleted")
Next
Dim script As ClientScriptManager = Page.ClientScript
script.RegisterStartupScript(GetType(Page), "RefreshProject", "parent.refreshNodeForProjects('" & Projects.objOrganization.intID.ToString() & ":company','" & Projects.objLocation.intID.ToString() & ":location" & "');") ' "parent.refreshNodeForProjects('" & Projects.objOrganization.intID.ToString() & ":company','" & Projects.objLocation.intID.ToString() & ":location" & "');", False)
If BSConfig.GetValue("ProjectsRefresh") = "1" Then
Response.Redirect(Request.RawUrl)
End If
End Sub
Here is the javascript function on the MasterPage:
function refreshNodeForProjects(company, location) {
try {
var tree = $find("<%= radprojecttree.ClientID %>");
if (company != '') {
rootnode = tree.findNodeByValue(company);
rootnode.set_expanded(false);
rootnode.get_treeView().trackChanges();
rootnode.get_nodes().clear();
rootnode.set_expandMode(2);
rootnode.get_treeView().commitChanges();
rootnode.set_selected(true);
rootnode.set_expanded(true);
if (location != '') {
rootnode = GetNodebyValue(rootnode, location);
rootnode.set_expanded(false);
rootnode.get_treeView().trackChanges();
rootnode.get_nodes().clear();
rootnode.set_expandMode(2);
rootnode.get_treeView().commitChanges();
rootnode.set_selected(true);
rootnode.set_expanded(true);
}
scrollToNode(tree, rootnode);
}
}
catch (ex) {
throw ex;
}
}
Created dynamic registered script block to handle this issue.

Can't access ExtJS radio button on form

So I have an .aspx page. In this grid I'm adding a bunch of controls. The first control however is an ExtObject, not one of our preset VB.NET controls. When I go to access the value on the backend for this field with this code:
form.AndOr.getValue()
It doesn't work. I really have no idea what is wrong. Basically, the radio button value isn't saving when I save the rest of the stuff. So I tried to add code to do it. It was just defaulted to 'And' each time. Below is a snippet of code from the actual asp.net grid. Any ideas?
With .Item(2)
.Ref = "../Payee2"
.LabelWidth = 90
With .AddFieldSet("Payee 2")
.AddControl(New Forms.Control("", "../PayeeId")).Hidden = True
.AddControl(New Forms.Control("", "../AddressId")).Hidden = True
.AddExtObject("{xtype:'radiogroup', ref:'../AndOr', defaults:{name:'rdo-payee2'}, width:120, items:[{boxLabel:'And', checked:true, inputValue:'and'},{boxLabel:'Or', inputValue:'or'}]}")
Dim ddlPayee2 As New Controls.ComboBox("", "../PayeePreInfo2", "Payee")
With ddlPayee2
.ForceSelection = True
.TypeAhead = False
.EmptyText = "Select Payee Details"
.ValueField = "AddressId"
.XTemplate = "applicantTemplate"
.ClientStore = "applicantAddressStore"
.AddListener(Akcelerant.Framework.WebControls.Controls.EventType.Select, "function(){prefillPayee('PAYEE2');}")
End With
.AddControl(ddlPayee2)
With .AddControl(New Forms.Control("", "../FirstName", "First Name", ""))
.Validate.MaxLength = 50
.ReadOnly = EditControl.IsFieldReadOnly(10483, True)
End With
With .AddControl(New Forms.Control("", "../LastName", "Last Name", ""))
.Validate.MaxLength = 50
.ReadOnly = EditControl.IsFieldReadOnly(10484, True)
End With
The error it throws is this:
Stack overflow at line: 16736
edit:
reverted some changes back and everything saves EXCEPT that value into the DB.
go to add this line to the javascript save function
if (form.AndOr.getValue() == 'and') {
payeeRec.set('IsPayee2RequiredToSign', 1);
} else {
payeeRec.set('IsPayee2RequiredToSign', 0);
}
and i get this error:
form.AndOr is not defined
Does the Ext ref: mean something different than my controls and how I access them?
Added a ref to the item of checkWin.
Then the ref to the radio value became
checkWin.Payee2.AndOr.getValue()
With that it can recognize the control on the form.

jquery masking/alerting problem in IE

I've got a table an input box that has a money input mask on it. I haven't had any problems with it yet, but now it doesn't seem to be working properly and I can't get anything to alert from it.
All of this is an internet explorer problem. Works fine in FireFox.
In firefox the mask works right as it only allows numbers and at a fixed format, but in ie, the format, or mask, is shown correctly when you're on focus, but as once you begin typing, the characters are being appended, rather than in place of the mask. It also is allowing non numeric characters. I've tried alerting in IE, but that also is not working. I can't find anything on this issue through google..
You'll have a better understanding of what it's doing if you check in firefox and then IE. It's the less advance cell at the bottom. or just append #less to the url.
I'll provide any code relevant to this..Though, I'm not getting any errors.
Code:
<td class="totals<cfif r EQ 1>1</cfif>"><cfif r EQ 1>Total<cfelse><input type="text" <cfif labels[r] EQ "Less Advance(if applicable)">id="less"</cfif><cfif labels[r] EQ "Net Due Employee">id="net"</cfif>id="totals" class="ttlR#r# total<cfif labels[r] EQ "Grand Total"> grandTot</cfif>" name="totals#r#" readonly="readonly" /></cfif></td>
$('#less').removeAttr("readonly").css("background-color", "none").css("text-align", "right").maskMoney({symbol: ""});
$('#less').keyup(function(){
$('#net').val(Number($('.grandTot').val() - $('#less').val()).toFixed(2));
alert($('#less').val());
});
//Get value of net total if page is refreshed.//
if($('#less').val() != "" || $('#less').val() != " "){
$('#net').val(Number($('.grandTot').val() - $('#less').val()).toFixed(2));
}
$('#less').keyup(function(){
$('#net').val(Number($('.grandTot').val() - $('#less').val()).toFixed(2));
alert($('#less').val());
});
You are quite likely overwriting your masking function with this. Take out everything but masking and then see if your masking works. If so then it is one of your additional functions overwriting the masking changes to the input box.
It doesn't look like the mask is being applied at all in IE. Which plugin are you using for the masking?
EDIT
I'm testing with IE 7.0.5730.13 and the mask doesn't work at all. Focusing-on and typing-in the <input> yields no special functionality, but it does throw an error
Line: 13
Char: 12949
Error: Invalid property value.
Code: 0
Have you tried debugging this with Firebug lite?
Also, you need to up your discipline with utilizing jQuery efficiently. Reuse Reuse Reuse!
var $less = $('#less')
, $net = $('#net')
, $grandTot = $('#totals .grandTot')
;
$less
.removeAttr( "readonly" )
.css( "background-color", "none" )
.css( "text-align", "right" )
.maskMoney( {symbol: ""} )
;
$net.bind( 'update-total', function()
{
$net.val( Number( parseFloat( $grandTot.val() ) - parseFloat( $less.val() ) ).toFixed( 2 ) );
} );
$less.keyup(function()
{
$net.trigger( 'update-total' );
alert( $less.val() );
});
//Get value of net total if page is refreshed.//
if ( $less.val() != "" || $less.val() != " " )
{
$net.trigger( 'update-total' );
}
Or just update to the newest version :)
https://github.com/plentz/jquery-maskmoney

Categories

Resources