2012-12-06 29 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

相关问题