2012-12-06 26 views
1

我正在用NPAPI寫一個safari插件。 如何從NPAPI插件(不使用FireBreath)返回一個整數到JavaScript? 的javascript:如何從NPAPI插件返回一個整數到JavaScript

<html> 
<head> 
<script> 
function run() { 
    var plugin = document.getElementById("pluginId"); 
    var number = plugin.getBrowserName(); 
    alert(number); 
} 
</script> 
</head> 
<body > 
<embed width="0" height="0" type="test/x-open-with-default-plugin" id="pluginId"> 
<button onclick="run()">run</button> 
</body> 
</html> 

插件代碼:

bool plugin_invoke(NPObject *obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { 
// Make sure the method called is "open". 
NPUTF8 *name = browser->utf8fromidentifier(methodName); 
if(strcmp(name, plugin_method_name_getBrowserName) == 0) { 
    //what can i do here? 
} 
return true; 

}

如何從plugin.getBrowserName返回一個數字()?

Plz help!

我發現這個線程:Return an integer/String from NPAPI plugin to JavaScript(Not using FireBreath), 但我不知道在哪裏,這些代碼

char* npOutString = (char *)pNetscapefn->memalloc(strlen(StringVariable) + 1); 
if (!npOutString) return false; strcpy(npOutString, StringVariable); 
STRINGZ_TO_NPVARIANT(npOutString, *result); 

放。

+0

取決於'utf8fromidentifier'是次優的,最好使用'static const NPIdentifier id = browser-> getstringidentifier(「foo」); if(methodName == id){...'。 –

回答

2

你看過http://npapi.com/tutorial3

返回值在NPVariant *結果中。看看docs for NPVariant,你會看到有一個類型,然後是不同類型數據的聯合。你說的字符串代碼會代替你的「//我能在這裏做什麼?」評論。返回一個整數,你可以這樣做:

bool plugin_invoke(NPObject *obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { 
// Make sure the method called is "open". 
NPUTF8 *name = browser->utf8fromidentifier(methodName); 
if(strcmp(name, plugin_method_name_getBrowserName) == 0) { 
    result->type = NPVariantType_Int32; 
    result->intValue = 42; 
} 
return true; 

您也可以使用* _TO_NPVARIANT宏(在上面NPVariant docs鏈接文件),像這樣:

bool plugin_invoke(NPObject *obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { 
// Make sure the method called is "open". 
NPUTF8 *name = browser->utf8fromidentifier(methodName); 
if(strcmp(name, plugin_method_name_getBrowserName) == 0) { 
    INT32_TO_NPVARIANT(42, *result); 
} 
return true; 

如果你看一下source for the INT32_TO_NPVARIANT macro你會看到它只是做了我以上所做的同樣的事情,所以這兩個是equivilent。

+1

非常感謝!這行得通! – justin

+0

優秀...現在請標記答案=](這是問題的複選標記大綱?點擊它,如果這是答案) – taxilian

相關問題