我想在全局函数中获取脚本的原始文件名。
我尝试了以下代码,但 filename.IsEmpty()返回true。
using namespace v8;
HandleScope handle_scope;
// Define Global Function 'func'
Handle<ObjectTemplate> global = ObjectTemplate::New();
auto func_name = v8::String::New("func");
auto func = v8::FunctionTemplate::New(
[](const v8::Arguments& args) -> v8::Handle<v8::Value>{
// I want to get Filename here.
auto filename = args.Callee()->GetScriptOrigin().ResourceName();
std::cout << filename.IsEmpty() << std::endl;
return v8::Undefined();
});
global->Set(func_name, func);
auto context = Context::New(nullptr, global);
Context::Scope context_scope(context);
auto source = String::New("func()");
// Set Filename
auto filename = String::New("abc.js");
auto script = v8::Script::Compile(source, filename);
script->Run();
context.Dispose();
是否有正确的方法来访问脚本的原始文件名?
答案 0 :(得分:3)
自己解决:
auto func = v8::FunctionTemplate::New(
[](const v8::Arguments& args) -> v8::Handle<v8::Value>{
// Get Filename
auto filename = v8::StackTrace::CurrentStackTrace(1,v8::StackTrace::kScriptName)
->GetFrame(0)->GetScriptName();
std::cout << *v8::String::AsciiValue(filename) << std::endl;
return v8::Undefined();
});