object top in VBScript - vbscript

Me and my teammate is getting hammered by this mystery.
While we are tracing some codes, we encounter something like this
top.VARIABLE_NAME
top.FunctionName(param)
We tried to trace the code for the object top, but it was not declared anywhere in the project, so we thought that it was a VBScript built-in object for global variables but there is not documentation for it.
so far we notice this line of code
ExecuteGlobal(strCode)
can this be the cause of that top object? please help us to understand this.
Update
It is weird but the HTML of our current project contains a lot of frames. but I don't know if that's the reason of using "top".
Here is the complete code/implementation for ExecuteGlobal(strCode)
Sub Import(ByVal strFile)
Dim objFs
Dim WshShell
Dim objFile
Dim strCode
Set objFs = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
WshShell.CurrentDirectory = "E:\MyFiles\Documents\Dev\Tester\VBS\haha"
Set objFile = objFs.OpenTextFile(strFile)
strCode = objFile.ReadAll
objFile.Close
ExecuteGlobal(strCode)
End Sub
if I print strCode, it contains this value.
sub HtmlCreator(arrObj)
for i = LBound(arrObj) to UBound(arrObj)
if not isEmpty(arrObj(i)) then
arrObj(i).innerHtml = "me"
end if
next
end sub
sorry I can't post the exact code because of confidentiality but I hope you get the idea.
THANKS..

top is the top level window in the DOM hierarchy.
Demo:
<html>
<head>
<script type="text/vbscript">
MsgBox TypeName(window.top) & " " & CStr(window.top Is top) & " " & CStr(window Is top)
</script>
</head>
<body>
</body>
</html>

Related

Updating Text Area with Status in HTA [duplicate]

In several of my .HTA scripts that I created, I had the need for the VBScript WScript.Sleep command which simply waits for a number of milliseconds without utilizing the CPU.
And when I browse the web, it appears that I am not the only one looking for this:
https://www.google.nl/search?q=hta+sleep
(I bet that if you read this, you probably need(ed) this as well)
The best solution that I could find appears to be the one which uses the PING command.
But especially for a situation were just need to pause the script for a few 100ms, this solution is quiet odd as it uses an external command and triggers all kind of (network) processes that unlikely have anything to do with the concerned .HTA script.
So the first thing that came to my mind was to use the WMI Win32_PingStatus class to avoid the external command but then I started to question why not completely basing it on WMI.
It has taken me several hours to get the right WMI classes and methods in place, but finally I succeeded…
When writing HTA's you should be thinking asynchronously. Consider rewriting your code to use window.setTimeout. In the following example, I will use window.setTimeout to make a bell sound every 2 seconds:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="ie=8">
<title>Bell Test</title>
<script language="VBScript">
Option Explicit
Dim objWShell
Set objWShell = CreateObject("WScript.Shell")
Sub DoPing
divText.innerText = Now
objWShell.Run "%COMSPEC% /c ECHO " & Chr(7), 0, False
window.setTimeOut "DoPing", 2000
End Sub
Sub window_OnLoad
window.ResizeTo 240,130
DoPing
End Sub
</script>
</head>
<body>
<div id="divText">TEST</div>
</body>
</html>
I had the same problem with HTA.
My solution with vbs ...
Sub sleep (Timesec)
Set objwsh = CreateObject("WScript.Shell")
objwsh.Run "Timeout /T " & Timesec & " /nobreak" ,0 ,true
Set objwsh = Nothing
End Sub
' example wait for 3 seconds
sleep 3
The routine will call a shell command, minimized and without a keyboard command.
Only ^C is permitted, but this will no user given in these situation.
Sub Sleep(iMilliSeconds)
With GetObject("winmgmts:\\.\root\cimv2")
With .Get("__IntervalTimerInstruction").SpawnInstance_()
.TimerId = "Sleep"
.IntervalBetweenEvents = iMilliSeconds
.Put_()
End With
.ExecNotificationQuery("SELECT * FROM __TimerEvent WHERE TimerId='Sleep'").NextEvent
End With
End Sub
Added 2015-02-11:
Unfortunately, this function doesn’t work when using Internet Explorer 10 (see comments below).
With Internet Explorer 11 installed, it appears to work if you run the HTA as administrator.
Wait(2000) 'pauses 2 seconds
Sub Wait(Time)
Dim wmiQuery, objWMIService, objPing, objStatus
wmiQuery = "Select * From Win32_PingStatus Where Address = '1.1.1.1' AND Timeout = " & Time
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objPing = objWMIService.ExecQuery(wmiQuery)
For Each objStatus in objPing
Next
End Sub
Sub Sleep (ms)
Set fso = CreateObject("Scripting.FileSystemObject")
Dim sFilePath: sFilePath = fso.GetSpecialFolder(2) & "\WScriptSleeper.vbs"
If Not fso.FileExists(sFilePath) Then
Set oFile = fso.CreateTextFile(sFilePath, True)
oFile.Write "wscript.sleep WScript.Arguments(0)"
oFile.Close
End If
Dim oShell: Set oShell = CreateObject("WScript.Shell")
oShell.Run sFilePath & " " & ms, 1, True
End Sub

Dynamic and recursive search for strings in windows Folder & subfolder

I am trying to implement a recursive search script with following usecase:-
User can input string and directory to search for.
Script will list all the files with path that matches point 1 (maybe in separate file).
I tried it with batch script and tried to run from html page to pass parameters (string and directory). It failed as mentioned over stackoverflow (due to javascripts inability to access file system.)
My batch script is :- findstr /s /i /n /C:#name= *.* v > results.txt
Now I am wondering if my requirement can be fulfilled with batch file or I need to switch to vbscript. Please suggest.
I have no Idea of vbscript.
I can not install any third party tool on my windows workstation.
This is vbscript and won't trigger security dialogs if run from a local page.
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
Searchterm = Inputbox("Enter search term")
ProcessFolder DirName
Sub ProcessFolder(FolderPath)
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
Set contents = thing.OpenAsTextStream
If Instr(contents.readall, searchterm) then wscript.echo thing.path
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
' wscript.echo thing.name
ProcessFolder thing.path
Next
End Sub
EDIT and EDIT2 (add browse for folder)
In an HTA (I had to start from scratch - I couldn't make your butchering of my script work).
<HTML>
<HEAD><TITLE>Simple Validation</TITLE>
<SCRIPT LANGUAGE="VBScript">
Dim Dirname
Dim Searchterm
Dim FSO
Dim objOutFile
Sub Browse
On Error Resume Next
Set bffShell = CreateObject("Shell.Application")
Set bff = bffShell.BrowseForFolder(0, "Select the My Documents folder", 9)
If Err.number<>0 Then
MsgBox "Error Setting up Browse for Folder"
Else
A = bff.ParentFolder.ParseName(bff.Title).Path
If err.number=424 then err.clear
tb2.value = A
End If
End Sub
Sub Search
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Set objOutFile = fso.CreateTextFile("results.txt",True)
Dirname = tb2.value
Searchterm = tb1.value
ProcessFolder DirName
End Sub
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
Set contents = thing.OpenAsTextStream
If err.number = 0 then
Test = Instr(contents.readall, searchterm)
If Isnull(test) = false then If Test > 0 then ObjOutFile.WriteLine thing.path
Else
err.clear
End If
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub
</script>
</head>
<body>
<p><INPUT Name=tb1 TYPE=Text Value="Search">
<p><INPUT Name=tb2 TYPE=Text Value="Folder"> <INPUT NAME="Browse" TYPE="BUTTON" VALUE="Browse" OnClick=Browse>
<p><INPUT NAME="Search" TYPE="BUTTON" VALUE="Search" OnClick=Search>
</body>
</html>

HTA and VBS dynamic list and opening file in list

First off new here and programming in general. I am trying to build an hta that can load various vbs scripts from an outside folder to make it more modular. I am current getting stuck at trying to open the vbs from my dynamic list. How do I open the file in my dynamic list? And also how do I pass a variable to the file? This is what I currently have:
<html>
<head>
<title>My HTML application</title>
<HTA:APPLICATION
APPLICATIONNAME="My HTML application"
ID="MyHTMLapplication"
VERSION="1.0"/>
</head>
<script language="VBScript">
Sub Window_OnLoad
Dim FolderPath
'folder to be searched for files
Dim objFSO
Dim objFolder
Dim colFiles
Dim objFile
Dim objOption
FolderPath = "%PathToScripts%"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(FolderPath)
Set colFiles = objFolder.Files
For Each objFile in colFiles
Set objOption = Document.createElement("OPTION")
objOption.Text = objFile.Name
objOption.Value = objFile.Name
mylistbox.Add(objOption)
Next
End Sub
Sub RunProgram
Set objShell = CreateObject("Wscript.Shell")
objShell.Run objOption
End Sub
</script>
<body bgcolor="white">
<!--Add your controls here-->
<select name="mylistbox" size=10>
</select>
<input type="button" value="SingleSelect" onclick="RunProgram" name="RunScript">
<!--{{InsertControlsHere}}-Do not remove this line-->
</body>
</html>
Question 1: How do I open the file in my dynamic list?
First, you need to retrieve the selected value from your list. For single-selection lists, you can just query the Value property of the <select> element:
strFile = mylistbox.Value
Since nothing may be selected, it's always a good idea to test the result to make sure you got something:
If Len(strFile) > 0 Then
Also, it looks like you're just showing the file name in the list, not the file path, which is fine, but you'll need the full file path if you want to run the file later. So you have a couple of options, here. Option 1: Make FolderPath a global constant instead of a local variable so that you can access it from your RunProgram() routine. Option 2: Take advantage of the Value property of <option> elements to store the full path for each list item while still just displaying the file name. Here's how to do the latter:
Set objOption = Document.createElement("OPTION")
objOption.Text = objFile.Name
objOption.Value = objFile.Path ' Changed from objFile.Name to objFile.Path
mylistbox.Add(objOption)
Next
Now that you have the full path to your script, you can run it. This is what your RunProgram() routine could look like:
Sub RunProgram()
' Get the selected value. This will be a full file path.
strFile = mylistbox.Value
' Make sure something was selected.
If Len(strFile) > 0 Then
' Run the script file.
Set objShell = CreateObject("WScript.Shell")
objShell.Run Chr(34) & strFile & Chr(34)
End If
End Sub
Note: Chr(34) is used to add double quotes around the file name in case it contains spaces.
Question 2: How do I pass a variable to the file?
This is where things get a little trickier. Though you can run a VBScript directly using the Shell.Run command (as we did above), if you want to pass an argument to the script, you need to run it explicitly using one of the scripting engine executables.
objShell.Run "wscript.exe " & Chr(34) & strFile & Chr(34) & " " & Chr(34) & strParam & Chr(34)
Here, we're using wscript.exe (the "GUI" version of the Windows Scripting Host) to explicitly run our script file. We're surrounding our file with double quotes, as we did above. And, finally, we're adding a space to separate the "command" from the parameter. For completeness, we're also adding double quotes around the parameter in case it contains spaces as well.

VB script works on Windows XP but not in Windows 7

I have a simple VBScript that I use in my webpage to rotate images located in a folder named "media\rotate". My script works fine when I run it in Windows XP but it does not work if I run it from Windows 7. I am using Windows 7 32Bit, while my Windows XP is a Service Pack 3.
My script looks like this:
Dim gRotatorFiles, gFileCount, gFileIndex
gFileCount = 0
gFileIndex = 1
Sub LoadRotatorImages()
Dim oFileSystem, oFolder, oFile
Set gRotatorFiles = CreateObject("POSCommonObjects.POSCollection")
Set oFileSystem = CreateObject("Scripting.FileSystemObject")
If oFileSystem.FolderExists("C:\Program Files\Customer Display\media\rotate") Then
Set oFolder = oFileSystem.GetFolder("C:\Program Files\Customer Display\media\rotate")
If Not oFolder Is Nothing Then
If Not oFolder.Files Is Nothing Then
For Each oFile In oFolder.Files
gRotatorFiles.Add oFile.Path, oFile.Name
Next
End If
End If
End If
gFileCount = gRotatorFiles.Count
Set oFileSystem = Nothing
Set oFolder = Nothing
Set oFile = Nothing
End Sub
Sub RotateImages()
If gFileCount > 0 Then
gFileIndex = gFileIndex + 1
If gFileIndex >= gFileCount Then
gFileIndex = 1
End If
LoadCurrentImage()
window.setTimeout "RotateImages()", 10000
End If
End Sub
Sub LoadCurrentImage()
document.all("AdImage").Filters(0).Apply
document.all("AdImage").src = gRotatorFiles(CInt(gFileIndex))
document.all("AdImage").Filters(0).Play
End Sub
Then I call it in my page like this:
<script language="vbscript" src="RotateImages.vbs"></script>
<script language="vbscript">
Sub Window_OnLoad()
RotateImages()
End Sub
</script>
And in the body:
<img id="AdImage" style="FILTER: prodig:DXImageTransform.Microsoft.GradientWipe(duration=2)" src="">
I wonder if someone knows what the inconsistencies between those operating systems might cause these issues or if it is something in my code.
To base the trouble shooting on something testable:
' On Error Resume Next
' global var used by LoadRotatorImages() and RotateImages()
Dim gRotatorFiles
' preparation: init gRotatorFiles
Sub LoadRotatorImages()
' Set gRotatorFiles = CreateObject("POSCommonObjects.POSCollection")
Set gRotatorFiles = CreateObject("System.Collections.ArrayList")
' Set gRotatorFiles = CreateObject("System.Collection.ArrayList")
gRotatorFiles.Add "fi"
gRotatorFiles.Add "fa"
gRotatorFiles.Add "fo"
End Sub
' real work: using gRotatorFiles
Sub RotateImages()
For Each f In gRotatorFiles
WScript.Echo f
Next
End Sub
' Then I call it in my page like this:
' but I forgot to call LoadRotatorImages()
LoadRotatorImages()
RotateImages()
output:
cscript 23547130.vbs
fi
fa
fo
First shot:
In the code you posted, you don't call LoadRotatorImages(). If adding this call does not fix your problem, disable the EVIL global OERN I suspect in your code and publish error messages.
Second shot:
"Not getting errors" is caused by an EVIL On Error Resume Next or (perhaps; I don't use IE) by some "Keep quiet about errors" setting(s) in the Internet Options. Evidence: If you activate the OERN and the bad CreateObject in the demo code, you get no output at all. After disabling The OERN again, you get a can't create object: 'System.Collection.ArrayList' message.
It's up to you whether you use OERN in your production code, but you shouldn't ask questions here without having tested your code without OERN (or equivalent IE settings).
If the code runs with neither error nor output even when "break on error" is on, try to add diagnostics for important pre-requisites. E.g.
' On Error Resume Next
...
Set gRotatorFiles = CreateObject("System.Collections.ArrayList")
' Set gRotatorFiles = CreateObject("System.Collection.ArrayList")
WScript.Echo "****", TypeName(gRotatorFiles)
...
results in:
cscript 23547130.vbs
**** ArrayList
If TypeName(gRotatorFiles) does not delivers something reasonable
double check the installation of the component
consider using a 'more native' collection (Scripting.Dictionary, ArrayList, ...)

get the target path from a nethood link

Let's say I have a nethood link to a folder with the name "BLABLA" and the target path is "\\servername\temp"
how do I get the string for the target path?
I tried:
Set oShell = CreateObject("WScript.Shell")
Const NET_HOOD = &H13&
Set oShApp = CreateObject("Shell.Application")
sNetHood = oShApp.NameSpace(NET_HOOD).Self.Path
Set oShortCut = oShell.CreateShortcut(sNetHood & "\" & "BLABLA" & ".lnk")
MsgBox "> " & oShortCut.TargetPath
It does everything, even creates a oShortCut object without any errors.
But, it does not return
oShortCut.TargetPath
what am I doing wrong?
I'd like it to return this: "\\servername\temp\BLABLA"
Thanks in advance for any advice!
I've created the shortcut under win 7 with right click in Computer view of the explorer and then > Add a network location > Next ... etc. It creates a Folder representing a shortcut in NetHood to the path on the server ... it's like a mapped share but not really it.
thx for the input ... after years of reading myself into the matter and then checking google once more i found a c# code which i wrote into vbs and then simplified only to see that all i had to change in the end was to add this:
.GetLink
so the solution to my problem is:
Const NET_HOOD = &H13&
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.NameSpace(NET_HOOD)
For Each oFile In oFolder.Items
MsgBox oFile.GetLink.Path
Next

Resources