Usage case (some info first):
I have made some HTML/CSS3/Javascript games that can run on different platforms in WebView/Embedded browser in a platform specific executable. I have designed it myself because I am tired of all the 'frameworks' that be around that told me how simple it is to use their framework. I don't need all the bloat of these frameworks with their impressive classes and stuff, it must be simple as ABC, right? Also because a webview is slower than native code, it must be simple and straight to get the best performance.
So I designed an interface that comes available as variable in javascript, no need to load an extra javascript class (like cordova or phonegap or others). Because I also work with Windows (Windows does not have the possibility to change the name of the object variable to 'publish'), it is accessible by javascript via window.external. This variable will be an object when the html is loaded inside a webview/browser.
Question
This all works pretty well (on different platforms) but the window.external
variable seems to be an empty object on Windows, but when you try to call a function like window.external.vibrate(500)
it will be executed without error (this function exists in all platform versions of this object).
However, something like typeof window.external.vibrate
results in 'undefined'
. Traversing the object does nothing, for example:
for( var p in window.external ) {
alert( p );
}
Because of this it is not easy to to test if the external object is a 'real' external object and it is not possible to see what functions are supported (if necessary).
What can I do about this? Do I miss something inhere?
To give you some information, I have followed this 'guide': http://www.delphidabbler.com/articles?article=22.
My code (simplified):
type library:
unit WebBrowserBridge_TLB;
// ************************************************************************ //
// WARNING
// -------
// The types declared in this file were generated from data read from a
// Type Library. If this type library is explicitly or indirectly (via
// another type library referring to this type library) re-imported, or the
// 'Refresh' command of the Type Library Editor activated while editing the
// Type Library, the contents of this file will be regenerated and all
// manual modifications will be lost.
// ************************************************************************ //
// PASTLWTR : $Revision: 1.88.1.0.1.0 $
// File generated on 4-3-2014 6:50:23 from Type Library described below.
// ************************************************************************ //
// Type Lib: ExternalInterface\WebBrowserBridge.tlb (1)
// IID\LCID: {517F7078-5E73-4E5A-A8A2-8F0FF14EF21B}\0
// Helpfile:
// DepndLst:
// (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb)
// ************************************************************************ //
{$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers.
interface
uses Windows, ActiveX, Classes, Graphics, OleServer, OleCtrls, StdVCL;
// *********************************************************************//
// GUIDS declared in the TypeLibrary. Following prefixes are used:
// Type Libraries : LIBID_xxxx
// CoClasses : CLASS_xxxx
// DISPInterfaces : DIID_xxxx
// Non-DISP interfaces: IID_xxxx
// *********************************************************************//
const
// TypeLibrary Major and minor versions
WebBrowserBridgeMajorVersion = 1;
WebBrowserBridgeMinorVersion = 0;
LIBID_WebBrowserBridge: TGUID = '{517F7078-5E73-XXXX-B8A2-8F0FF14EF21B}';
IID_IWebBrowserBridge: TGUID = '{4F995D09-XXXX-4042-993E-C71A8AED661E}';
type
// *********************************************************************//
// Forward declaration of types defined in TypeLibrary
// *********************************************************************//
IWebBrowserBridge = interface;
IWebBrowserBridgeDisp = dispinterface;
// *********************************************************************//
// Interface: IWebBrowserBridge
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {4F995D09-CF9E-XXX-993E-C71A8AED661E}
// *********************************************************************//
IWebBrowserBridge = interface(IDispatch)
['{4F995D09-CF9E-4042XXXX-C71A8AED661E}']
procedure isAvailable; safecall;
procedure vibrate(ms: Integer); safecall;
end;
// *********************************************************************//
// DispIntf: IWebBrowserBridgeDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {4F995D09-CF9E-XXX-993E-C71A8AED661E}
// *********************************************************************//
IWebBrowserBridgeDisp = dispinterface
['{4F995D09-CF9E-404XXXE-C71A8AED661E}']
procedure isAvailable; dispid 200;
procedure vibrate(ms: Integer); dispid 201;
end;
implementation
uses ComObj;
end.
Object library (class):
unit WebBrowserBridge;
interface
uses
// Delphi
ActiveX, SHDocVw, Windows, Classes, ComObj, Dialogs,
// Project
IntfDocHostUIHandler, UNulContainer, WebBrowserBridge_TLB;
type
TWebBrowserBridge = class(TAutoIntfObject, IWebBrowserBridge, IDispatch)
public
{ IMyExternal methods }
procedure isAvailable(); safecall;
procedure vibrate(ms: Integer); safecall;
public
constructor Create;
destructor Destroy; override;
end;
{
TWebBrowserBridgeContainer:
UI handler that extends browser's external object.
}
TWebBrowserBridgeContainer = class(TNulWBContainer, IDocHostUIHandler, IOleClientSite)
private
fExternalObj: IDispatch; // external object implementation
protected
{ Re-implemented IDocHostUIHandler method }
function GetExternal(out ppDispatch: IDispatch): HResult; stdcall;
public
constructor Create(const WBDefaultInterface: IDispatch);
end;
implementation
uses
SysUtils, StdActns;
{ TWebBrowserBridgeContainer }
constructor TWebBrowserBridgeContainer.Create(const WBDefaultInterface: IDispatch);
begin
inherited;
fExternalObj := TWebBrowserBridge.Create;
end;
function TWebBrowserBridgeContainer.GetExternal(out ppDispatch: IDispatch): HResult;
begin
ppDispatch := fExternalObj;
Result := S_OK; // indicates we've provided script
end;
{ TWebBrowserBridge }
constructor TWebBrowserBridge.Create;
var
TypeLib: ITypeLib; // type library information
ExeName: WideString; // name of our program's exe file
begin
// Get name of application
ExeName := ParamStr(0);
// Load type library from application's resources
OleCheck(LoadTypeLib(PWideChar(ExeName), TypeLib));
// Call inherited constructor
inherited Create(TypeLib, IWebBrowserBridge);
end;
destructor TWebBrowserBridge.Destroy;
begin
inherited;
end;
procedure TWebBrowserBridge.isAvailable();
begin
//Result:=1;
end;
procedure TWebBrowserBridge.vibrate(ms: Integer);
begin
windows.beep( 100, ms );
//showMessage( IntToStr( ms ));
end;
PS:
I also want to know how to create a function in the type library because it only allows to create procedures or properties (but properties are not supported like on Android).
EDIT:
See also my answer but question is still open because of the PS above.
To get this working:
You would need to implement
IDispatchEx
on yourexternal
object, specificallyIDispatchEx::GetNextDispID
andIDispatchEx::GetMemberName
. This is how JavaScript iterates through COM object properties.You could find some more details about
IDispatchEx
here.It's not a real answer because it doesn't explain why traversing the object is not possible (but there is some explanation in the answer of Noseratio but unable to get it done myself so not able to verify it), but okay I can test if some function exists by using the following javascript code:
When you take a look at the example above, it is weird that the following code doesn't work (because of the 'in' operator):
Because Firefox does also implement a window.external object but with other intent (see also: https://developer.mozilla.org/en-US/docs/Adding_search_engines_from_web_pages), I check for the function 'isAvailable' that will be exported by the javascript external interface. To check if it is a real interface object, I do the following (the variable 'o' is an object):
If you know a better solution please let me know.
It is possible to use a much simpler approach to implement
external
methods in Delphi, using the late-bound functionality provided by ObjComAuto.TObjectDispatch.This way you don't need to define any interfaces nor a type library. All what you need is a simple class implementing the desired events, and the extended RTTI info provided by $METHODINFO.
You can implement procedures and functions, and receive Delphi types or javascript objects as parameters. Javascript objects can also be used from Delphi (both properties and methods can be accessed).
Example: (just drop a TEmbeddedWB in a form)
Note:
Javascript arrays are sparse, so you can't access them from Delphi using the usual
myArray[3]
syntax. Instead you need to use the index as if it were a property, i.e. some kind ofmyArray.3
. This is not directly supported by Delphi, but using ComObj.GetDispatchPropValue:GetDispatchPropValue(myArray, '3')
. More info here.Edit:
See my other answer for info on how to iterate thru
window.external
methods.How to create functions in the type library
Automation methods are functions returning
HRESULT
, converted to procedures by Delphi safecall calling convention, that automatically manage HRESULTs.In addition to in and out parameters, automation methods also support one retval parameter. Delphi converts methods with it to a safecall function using the parameter type as the result type of the function. The retval parameter must be the last one and, as an out parameter, has to be a pointer (e.g.,
long*
instead oflong
for integers,BSTR*
instead ofBSTR
for strings, ...).So, if you declare in the type library editor a parameter with a pointer type and the out and retval modifiers, it will appear in the *_TLB.pas file as a safecall function. This is also the way that property getters are created.
Iterating thru
window.external
methodsAs Noseratio said, the dispatch object must implement IDispatchEx.
I've made a library with two classes which extend
TAutoIntfObject
andTObjectDispatch
so they implement the basic functionality of IDispatchEx.So if you inherit your
TWebBrowserBridge
fromTAutoIntfObjectEx
instead ofTAutoIntfObject
, now the iterating will work.To implement
GetNextDispID
andGetMemberName
, both classes need to extract metadata about the methods of the class:TAutoIntfObjectEx
obtains it from theITypeInfo
provided by the type library.TObjectDispatchEx
obtains it from the extended RTTI provided by{$METHODINFO ON}
.This needs at least Delphi 2010. See my other answer for info on how to use
TObjectDispatch
.The metadata is used in each iteration of the
for in
, so, for each class inherited from one of them, it is extracted the first time it's needed and cached for subsequent uses. This means a two-level cache: one for each subclass inherited from one of the extended classes, and other for the dispids and names of each subclass' methods.I've used a somewhat rough approach with sorted
TStringList
and binary search for both caches. The first level can be replaced with an unsorted map (like a hashtable, e.g.TObjectDictionary
in modern Delphi versions), but the second needs also ordering, so a sorted map (like a Red-black tree) is the right way.