如何创建js内部对象
1. 使用IActiveScript::AddNamedItem添加需要响应的内部对象
HRESULT hr;
IActiveScript* pScript;
CLSID clsid;
// Search for LanguageID and create instance of script engine
if (SUCCEEDED(CLSIDFromProgID(L"JScript", &clsid)))
{
// If this happens, the scripting engine is probably not properly registered
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IActiveScript, (void **)&pScript);
if(SUCCEEDED(hr)) {
pScript->AddNameItem(L"newname", SCRIPTITEM_ISVISIBLE|SCRIPTITEM_ISSOURCE);
pScript->Release();
}
}
2. 绑定COM到新的名字对象上, 创建一个新的com对象, 比如接口名叫INewName
实现一个IActiveScriptSite接口, 并实现里面的GetItemInfo方法
class CMyActiveScriptSite : public IActiveScriptSite
{
HRESULT GetItemInfo(
LPCOLESTR pstrName, // address of item name
DWORD dwReturnMask, // bit mask for information retrieval
IUnknown **ppunkItem, // address of pointer to item's IUnknown
ITypeInfo **ppTypeInfo // address of pointer to item's ITypeInfo
)
{
if(_wcsicmp(L"newname", pstrName) == 0)
{
if (dwReturnMask & SCRIPTINFO_ITYPEINFO)
{
LPUNKNOWN lpUnknown = NULL;
// 获取INewName
// ...
lpUnknown = pNewName;
// Use IProvideClassInfo to get ITypeInfo of coclass!
IProvideClassInfo *pci = NULL;
HRESULT hr = lpUnknown->QueryInterface(IID_IProvideClassInfo, (void**)&pci);
if (SUCCEEDED(hr) && pci)
{
hr = pci->GetClassInfo(ppti);
}
// Release interface
if (pci)
pci->Release();
if (FAILED(hr))
return E_FAIL;
}
if (dwReturnMask & SCRIPTINFO_IUNKNOWN)
{
*ppiunkItem = lpUnknown;
(*ppiunkItem)->AddRef(); // because returning
}
}
}
}
CMyActiveScriptSite* pSite = new CMyActiveScriptSite;
pScript->SetScriptSite(pSite);
3. 脚本里使用INewName的接口, 比如INewName实现了run这个接口
<SCRIPT LANGUAGE="JavaScript">
<!--
newname.run();
//-->
</SCRIPT>
最终脚本将把newname看成和window一样的内部对象
posted on 2010-01-12 20:35
wangkang 阅读(458)
评论(0) 编辑 收藏 引用