#include "JSValueHelper.h" #include #include std::string JS2String(v8::Local object) { v8::Isolate *isolate = v8::Isolate::GetCurrent(); v8::HandleScope handleScope(isolate); v8::Local context = isolate->GetEnteredOrMicrotaskContext(); if (object->IsString() || object->IsRegExp() || object->IsFunction()) { v8::String::Utf8Value utf8(isolate, object); return std::string(*utf8); } if (object->IsObject()) { v8::MaybeLocal str = v8::JSON::Stringify( context, object->ToObject(context).ToLocalChecked()); if (str.IsEmpty()) { return ""; } v8::Local s = str.ToLocalChecked(); v8::String::Utf8Value str2(isolate, s); return std::string(*str2 ? *str2 : ""); } v8::String::Utf8Value str( isolate, v8::JSON::Stringify(context, object).ToLocalChecked()); return std::string(*str ? *str : ""); } double JS2Number(v8::Local value) { v8::HandleScope handleScope(v8::Isolate::GetCurrent()); v8::Local context = v8::Isolate::GetCurrent()->GetCurrentContext(); if (value->IsNumber()) { return value->ToNumber(context).ToLocalChecked()->Value(); } else { return 0; } } bool JS2Bool(v8::Local value) { v8::HandleScope handleScope(v8::Isolate::GetCurrent()); if (value->IsBoolean()) { return value->ToBoolean(v8::Isolate::GetCurrent())->Value(); } else { return false; } } v8::Local String2JS(std::string string) { v8::Isolate *isolate = v8::Isolate::GetCurrent(); v8::EscapableHandleScope handleScope(isolate); v8::Local context = isolate->GetEnteredOrMicrotaskContext(); v8::Local jsString = NewV8String(string.c_str()); v8::Local ret = v8::JSON::Parse(context, jsString).ToLocalChecked(); return handleScope.Escape(ret); } v8::Local Variant2JS(QVariant variant) { v8::Isolate *isolate = v8::Isolate::GetCurrent(); v8::EscapableHandleScope handle_scope(isolate); v8::Local jsValue; if (variant.type() == QVariant::String) { jsValue = NewV8String(variant.toString().toUtf8().constData()); } else if (variant.type() == QVariant::Map) { QMap map = variant.toMap(); QJsonObject jsonObject; foreach (QString key, map.keys()) { QVariant value = map.value(key); jsonObject.insert(key, QJsonValue::fromVariant(value)); } QJsonDocument doc(jsonObject); QString strJson(doc.toJson(QJsonDocument::Compact)); jsValue = String2JS(strJson.toUtf8().constData()); } else if (variant.type() == QVariant::StringList) { qDebug() << ""; } return handle_scope.Escape(jsValue); }