我正在用NPAPI编写一个safari插件。 如何从NPAPI插件(不使用FireBreath)返回一个整数到JavaScript? 的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帮助!
我找到了这个帖子: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 :(得分: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,你会看到它与我上面做的一样,所以两者是等价的。