WB.Document.parentWindow (and
WB.Document.Script, actually) refer to the
window object, which is where all global variables live. You can store a function reference (
Func("FuncName")) or any other object in the window object and it will be accessible to the page's scripts. You can also call functions defined in the script via the window object, and pass function references or other objects.
If the Notification "class" already exists in the page you're loading, you probably don't need to add any JavaScript; you can just pass it a reference to your function. Otherwise, there are a few methods to add/execute script:
- window.eval(js) will evaluate js and give you a result, but it seems to fail fairly often if the page is in an older document mode (WB.Document.documentMode). The WebBrowser control operates in IE7 or IE5 mode by default, depending on the !DOCTYPE. You can override it with the FEATURE_BROWSER_EMULATION registry key or putting <meta http-equiv="X-UA-Compatible" content="IE=edge"> in the document.
- window.execScript(js) generally works but has no return value.
- Creating a script element dynamically, as you might in JavaScript.
The way that you define
Notification and the way that you use it do not match up (the JavaScript you've posted will never work). I suppose that either it would have to be defined like
Notification.Notification = function(...) { ... } or called like
(new Notification).Notification(...).
Code: Select all
Gui, 1: Add, ActiveX, x0 y0 w300 h500 vWB, Shell.Explorer
Gui, Show, w800 h500, test
scriptToInject =
(
function Notification() {
this.Notification = function(title, options) {
WB_NotificationCallback(title,options);
}
}
(new Notification).Notification("Test notification.")
)
WB.Silent := True
WB.Navigate("http://example.com")
while WB.ReadyState != 4
Sleep 100
WB.Document.parentWindow.WB_NotificationCallback := Func("WB_NotificationCallback")
WB.Document.parentWindow.execScript(scriptToInject)
WB_NotificationCallback(text) {
TrayTip, New Notification, % text
}
GuiClose() {
ExitApp
}
If execScript and eval don't work, an alternative is
LoadJS(WB.Document, scriptToInject):
Code: Select all
LoadJS(document, js) {
script := document.createElement("script")
script.type := "text/javascript"
script.text := js
document.getElementsByTagName("head").item(0).appendChild(script)
}
The script might be executed asynchronously, so if you need to know when it's complete, you can either have
js call a global function which you pre-define, or store a function reference in
script.onload.
You can load external JS files by using
src instead of
text.
jethrow wrote:this focuses more on having your AHK script respond to webpage events
If the idea is for the AutoHotkey script to hook into a custom JavaScript-based API (Notification.Notification), then the ComObjConnect() method you've demonstrated is very unlikely to work.