1# Setting JS Object Properties Using JSVM-API 2 3## Introduction 4 5This topic walks you through on how to obtain and set properties of a JavaScript (JS) object using JSVM-API. Properly using these APIs help to implement more complex functionalities and logic. 6 7## Basic Concepts 8 9Before working with JS objects using JSVM-API, you need to understand the following concepts: 10 11- Object: a composite data type that allows values of different types in an independent entity in JS. An object is a collection of properties and methods. A property is a value associated with the object, and a method is an operation that the object can perform. 12- Property: a feature, in the key-value format, of an object in JS. Each property has a name (key or identifier) and a value. The property value can be of any data type, including the basic type, object, and function. 13- Enumerable property: a property in JS with **enumerable** set to **true**. An enumerable property can be traversed by **for...in**. 14- Own property: a property defined for an object rather than inherited from the prototype chain. 15 16## Available APIs 17 18| API | Description | 19|----------------------------|--------------------------------| 20| OH_JSVM_GetPropertyNames | Obtains the names of all enumerable properties of a JS object as a JS array. | 21| OH_JSVM_SetProperty | Sets a property for a JS object. | 22| OH_JSVM_GetProperty | Obtains a property from a JS object. | 23| OH_JSVM_HasProperty | Checks whether a JS object has the specified property. | 24| OH_JSVM_DeleteProperty | Deletes a property from a JS object. | 25| OH_JSVM_HasOwnProperty | Checks whether an object has the own property specified by **key**.| 26| OH_JSVM_SetNamedProperty | Sets a property with the given property name for a JS object. This API is equivalent to calling **OH_JSVM_SetNamedProperty** with a **JSVM_Value** created from the string passed in as **utf8Name**.| 27| OH_JSVM_GetNamedProperty | Obtains a property from a JS object. This API is equivalent to calling **OH_JSVM_GetNamedProperty** with a **JSVM_Value** created from the string passed in as **utf8Name**.| 28| OH_JSVM_HasNamedProperty | Checks whether a JS object has the specified property. This API is equivalent to calling **OH_JSVM_HasProperty** with a **JSVM_Value** created from the string passed in as **utf8Name**.| 29| OH_JSVM_DefineProperties | Defines multiple properties for a JS object. | 30| OH_JSVM_GetAllPropertyNames | Obtains the names of all available properties of a JS object as a JS array. | 31 32## Example 33 34If you are just starting out with JSVM-API, see [JSVM-API Development Process](use-jsvm-process.md). The following demonstrates only the C++ and ArkTS code related to JS property APIs. 35 36### OH_JSVM_GetPropertyNames 37 38Use **OH_JSVM_GetPropertyNames** to obtain names of all enumerable properties of a JS object in the form of a string array. If the operation is successful, **JSVM_OK** is returned. 39 40CPP code: 41 42```cpp 43// Register the GetPropertyNames callback. 44static JSVM_CallbackStruct param[] = { 45 {.data = nullptr, .callback = GetPropertyNames}, 46}; 47static JSVM_CallbackStruct *method = param; 48// Set a property descriptor named getPropertyNames and associate it with a callback. This allows the CreateStringLatin1 callback to be called from JS. 49static JSVM_PropertyDescriptor descriptor[] = { 50 {"getPropertyNames", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 51}; 52// Define OH_JSVM_GetPropertyNames. 53static JSVM_Value GetPropertyNames(JSVM_Env env, JSVM_CallbackInfo info) 54{ 55 // Pass in obj as a parameter. 56 size_t argc = 1; 57 JSVM_Value args[1] = {nullptr}; 58 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 59 // Obtain the names of all the enumerable properties of the object in the form of a string array and output the string array in result. 60 JSVM_Value result = nullptr; 61 JSVM_Status status = OH_JSVM_GetPropertyNames(env, args[0], &result); 62 if (status != JSVM_OK) { 63 OH_JSVM_ThrowError(env, nullptr, "Failed to get propertynames"); 64 return nullptr; 65 } else { 66 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_GetPropertyNames success"); 67 } 68 return result; 69} 70``` 71 72ArkTS code: 73 74```ts 75import hilog from "@ohos.hilog" 76// Import the native APIs. 77import napitest from "libentry.so" 78let obj = '{ data: 0, message: "hello world"}'; 79let script: string = `getPropertyNames(${obj})`; 80try { 81 let result = napitest.runJsVm(script); 82 hilog.info(0x0000, 'testJSVM', 'Test JSVM getPropertyNames: %{public}s', result); 83} catch (error) { 84 hilog.error(0x0000, 'testJSVM', 'Test JSVM getPropertyNames error: %{public}s', error.message); 85} 86``` 87 88### OH_JSVM_SetProperty 89 90Use **OH_JSVM_SetProperty** to set a property for an object. 91 92CPP code: 93 94```cpp 95// Register the SetProperty callback. 96static JSVM_CallbackStruct param[] = { 97 {.data = nullptr, .callback = SetProperty}, 98}; 99static JSVM_CallbackStruct *method = param; 100// Set a property descriptor named setProperty and associate it with a callback. This allows the SetProperty callback to be called from JS. 101static JSVM_PropertyDescriptor descriptor[] = { 102 {"setProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 103}; 104// Define OH_JSVM_SetProperty. 105static JSVM_Value SetProperty(JSVM_Env env, JSVM_CallbackInfo info) 106{ 107 // Obtain the parameters passed from JS. The first parameter specifies the object, the second parameter specifies the property name, and the third parameter specifies the property value to set. 108 size_t argc = 3; 109 JSVM_Value args[3] = {nullptr}; 110 JSVM_Status status = OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 111 if (status != JSVM_OK) { 112 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_GetCbInfo fail"); 113 return nullptr; 114 } 115 // Call OH_JSVM_SetProperty to set the property name and value to the object. If the operation fails, an error is thrown. 116 status = OH_JSVM_SetProperty(env, args[0], args[1], args[2]); 117 if (status != JSVM_OK) { 118 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_SetProperty fail"); 119 return nullptr; 120 } else { 121 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_SetProperty success"); 122 } 123 // Return the object that is successfully set. 124 return args[0]; 125} 126``` 127 128ArkTS code: 129 130```ts 131import hilog from "@ohos.hilog" 132// Import the native APIs. 133import napitest from "libentry.so" 134let script: string = ` 135 let obj = { data: 0, message: "hello world", 50: 1}; 136 setProperty(obj, "code", "hi") 137` 138try { 139 let result = napitest.runJsVm(script); 140 hilog.info(0x0000, 'testJSVM', 'Test JSVM setProperty: %{public}s', result); 141} catch (error) { 142 hilog.error(0x0000, 'testJSVM', 'Test JSVM setProperty error: %{public}s', error.message); 143} 144``` 145 146### OH_JSVM_GetProperty 147 148Use **OH_JSVM_GetProperty** to obtain a property value of a JS object based on the property name. 149 150CPP code: 151 152```cpp 153// Register the GetProperty callback. 154static JSVM_CallbackStruct param[] = { 155 {.data = nullptr, .callback = GetProperty}, 156}; 157static JSVM_CallbackStruct *method = param; 158// Set a property descriptor named getProperty and associate it with a callback. This allows the GetProperty callback to be called from JS. 159static JSVM_PropertyDescriptor descriptor[] = { 160 {"getProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 161}; 162// Define OH_JSVM_GetProperty. 163static JSVM_Value GetProperty(JSVM_Env env, JSVM_CallbackInfo info) 164{ 165 // Obtain the two parameters passed from JS. 166 size_t argc = 2; 167 JSVM_Value args[2] = {nullptr}; 168 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 169 // The first parameter specifies the target object, and the second specifies the property name. Call OH_JSVM_GetProperty to obtain the value of the property. 170 JSVM_Value result = nullptr; 171 JSVM_Status status = OH_JSVM_GetProperty(env, args[0], args[1], &result); 172 if (status != JSVM_OK) { 173 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_GetProperty fail"); 174 return nullptr; 175 } else { 176 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_GetProperty success"); 177 } 178 return result; 179} 180``` 181 182ArkTS code: 183 184```ts 185import hilog from "@ohos.hilog" 186// Import the native APIs. 187import napitest from "libentry.so" 188let script: string = ` 189 let obj = { data: 0, message: "hello world", 50: 1}; 190 getProperty(obj, "message") 191` 192try { 193 let result = napitest.runJsVm(script); 194 hilog.info(0x0000, 'testJSVM', 'Test JSVM getProperty: %{public}s', result); 195} catch (error) { 196 hilog.error(0x0000, 'testJSVM', 'Test JSVM getProperty error: %{public}s', error.message); 197} 198``` 199 200### OH_JSVM_HasProperty 201 202Use **OH_JSVM_HasProperty** to check whether an object has the specified property. This can prevent the exception or error caused by access to a property that does not exist. 203 204CPP code: 205 206```cpp 207// Register the HasProperty callback. 208static JSVM_CallbackStruct param[] = { 209 {.data = nullptr, .callback = HasProperty}, 210}; 211static JSVM_CallbackStruct *method = param; 212// Set a property descriptor named hasProperty and associate it with a callback. This allows the HasProperty callback to be called from JS. 213static JSVM_PropertyDescriptor descriptor[] = { 214 {"hasProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 215}; 216// Define OH_JSVM_HasProperty. 217static JSVM_Value HasProperty(JSVM_Env env, JSVM_CallbackInfo info) 218{ 219 // Pass in two parameters from JS. The first parameter specifies the target object, and the second parameter specifies the property to check. 220 size_t argc = 2; 221 JSVM_Value args[2] = {nullptr}; 222 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 223 // Pass the parameters to OH_JSVM_HasProperty. If the API is successfully called, convert the result to JSVM_Value and return JSVM_Value. Otherwise, throw an error. 224 bool result; 225 JSVM_Status status = OH_JSVM_HasProperty(env, args[0], args[1], &result); 226 if (status != JSVM_OK) { 227 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_HasProperty fail"); 228 return nullptr; 229 } else { 230 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_HasProperty success:%{public}d", result); 231 } 232 // If the property exists in the object, output true, convert the result to JSVM_Value, and return JSVM_Value. 233 JSVM_Value returnReslut = nullptr; 234 OH_JSVM_GetBoolean(env, result, &returnReslut); 235 return returnReslut; 236} 237``` 238 239ArkTS code: 240 241```ts 242import hilog from "@ohos.hilog" 243// Import the native APIs. 244import napitest from "libentry.so" 245let script: string = ` 246 let obj = { data: 0, message: "hello world", 50: 1}; 247` 248let scriptTrue: string = script + `\n` + ` 249 hasProperty(obj, "data") 250` 251let scriptFalse: string = script + `\n` + ` 252 hasProperty(obj, 0) 253` 254try { 255 let resultTrue = napitest.runJsVm(scriptTrue); 256 hilog.info(0x0000, 'testJSVM', 'Test JSVM HasProperty: %{public}s', resultTrue); 257 let resultFalse = napitest.runJsVm(scriptFalse); 258 hilog.info(0x0000, 'testJSVM', 'Test JSVM HasProperty: %{public}s', resultFalse); 259} catch (error) { 260 hilog.error(0x0000, 'testJSVM', 'Test JSVM hasProperty error: %{public}s', error.message); 261} 262``` 263 264### OH_JSVM_DeleteProperty 265 266Use **OH_JSVM_DeleteProperty** to delete the property specified by **key** from an object. 267If the object is a non-extensible object or the property is not configurable, the property cannot be deleted. 268 269CPP code: 270 271```cpp 272// Register the DeleteProperty callback. 273static JSVM_CallbackStruct param[] = { 274 {.data = nullptr, .callback = DeleteProperty}, 275}; 276static JSVM_CallbackStruct *method = param; 277// Set a property descriptor named deleteProperty and associate it with a callback. This allows the DeleteProperty callback to be called from JS. 278static JSVM_PropertyDescriptor descriptor[] = { 279 {"deleteProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 280}; 281// Define OH_JSVM_DeleteProperty. 282static JSVM_Value DeleteProperty(JSVM_Env env, JSVM_CallbackInfo info) 283{ 284 // Obtain the two parameters passed from JS. 285 size_t argc = 2; 286 JSVM_Value args[2] = {nullptr}; 287 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 288 JSVM_ValueType valueType; 289 OH_JSVM_Typeof(env, args[0], &valueType); 290 if (valueType != JSVM_OBJECT) { 291 OH_JSVM_ThrowError(env, nullptr, "Expects an object as argument."); 292 return nullptr; 293 } 294 // Delete the specified property from the object and return a bool value indicating whether the deletion is successful. 295 bool result = false; 296 JSVM_Status status = OH_JSVM_DeleteProperty(env, args[0], args[1], &result); 297 if (status != JSVM_OK) { 298 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_DeleteProperty failed"); 299 return nullptr; 300 } else { 301 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_DeleteProperty success:%{public}d", result); 302 } 303 // Convert the bool value to JSVM_value and return JSVM_value. 304 JSVM_Value ret; 305 OH_JSVM_GetBoolean(env, result, &ret); 306 return ret; 307} 308``` 309 310ArkTS code: 311 312```ts 313import hilog from "@ohos.hilog" 314// Import the native APIs. 315import napitest from "libentry.so" 316let script: string = ` 317 let obj = { data: 0, message: "hello world", 50: 1}; 318 deleteProperty(obj, "message") 319` 320try { 321 let result = napitest.runJsVm(script); 322 hilog.info(0x0000, 'testJSVM', 'Test JSVM deleteProperty: %{public}s', result); 323} catch (error) { 324 hilog.error(0x0000, 'testJSVM', 'Test JSVM deleteProperty error: %{public}s', error.message); 325} 326``` 327 328### OH_JSVM_HasOwnProperty 329 330Use **OH_JSVM_HasOwnProperty** to check whether a JS object has its own property. 331 332CPP code: 333 334```cpp 335// Register the HasOwnProperty callback. 336static JSVM_CallbackStruct param[] = { 337 {.data = nullptr, .callback = HasOwnProperty}, 338}; 339static JSVM_CallbackStruct *method = param; 340// Set a property descriptor named hasOwnProperty and associate it with a callback. This allows the HasOwnProperty callback to be called from JS. 341static JSVM_PropertyDescriptor descriptor[] = { 342 {"hasOwnProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 343}; 344// Define OH_JSVM_HasOwnProperty. 345static JSVM_Value HasOwnProperty(JSVM_Env env, JSVM_CallbackInfo info) 346{ 347 // Obtain the two parameters passed from JS. 348 size_t argc = 2; 349 JSVM_Value args[2] = {nullptr}; 350 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 351 // Check whether the first parameter is an object. 352 JSVM_ValueType valueType1; 353 OH_JSVM_Typeof(env, args[0], &valueType1); 354 if (valueType1 != JSVM_OBJECT) { 355 OH_JSVM_ThrowError(env, nullptr, "First argument must be an object."); 356 return nullptr; 357 } 358 // Check whether the second parameter is a string. 359 JSVM_ValueType valuetype2; 360 OH_JSVM_Typeof(env, args[1], &valuetype2); 361 if (valuetype2 != JSVM_STRING ) { 362 OH_JSVM_ThrowError(env, nullptr, "Second argument must be a string."); 363 return nullptr; 364 } 365 // Check whether the object has the specified property and return the result in hasProperty. 366 bool hasProperty; 367 JSVM_Status status = OH_JSVM_HasOwnProperty(env, args[0], args[1], &hasProperty); 368 if (status != JSVM_OK) { 369 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_HasOwnProperty failed"); 370 return nullptr; 371 } else { 372 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_HasOwnProperty success:%{public}d", hasProperty); 373 } 374 // Convert the bool value to JSVM_Value and return JSVM_value. 375 JSVM_Value result; 376 OH_JSVM_GetBoolean(env, hasProperty, &result); 377 return result; 378} 379``` 380 381ArkTS code: 382 383```ts 384import hilog from "@ohos.hilog" 385// Import the native APIs. 386import napitest from "libentry.so" 387let script: string = ` 388 let obj = { data: 0, message: "hello world", 50: 1}; 389` 390let scriptTrue: string = script + `\n` + ` 391 hasOwnProperty(obj, "message") 392` 393let scriptFalse: string = script + `\n` + ` 394 hasOwnProperty(obj, "__defineGetter__") 395` 396try { 397 let resultTrue = napitest.runJsVm(scriptTrue); 398 hilog.info(0x0000, 'testJSVM', 'Test JSVM hasOwnProperty: %{public}s', resultTrue); 399 let resultFalse = napitest.runJsVm(scriptFalse); 400 hilog.info(0x0000, 'testJSVM', 'Test JSVM hasOwnProperty: %{public}s', resultFalse); 401} catch (error) { 402 hilog.error(0x0000, 'testJSVM', 'Test JSVM hasOwnProperty error: %{public}s', error.message); 403} 404``` 405 406### OH_JSVM_SetNamedProperty 407 408Use **OH_JSVM_SetNamedProperty** to set a property for a JS object. 409 410CPP code: 411 412```cpp 413// Register the SetNamedProperty callback. 414static JSVM_CallbackStruct param[] = { 415 {.data = nullptr, .callback = SetNamedProperty}, 416}; 417static JSVM_CallbackStruct *method = param; 418// Set a property descriptor named SetNamedProperty and associate it with a callback. This allows the SetNamedProperty callback to be called from JS. 419static JSVM_PropertyDescriptor descriptor[] = { 420 {"setNamedProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 421}; 422// Define OH_JSVM_SetNamedProperty. 423static JSVM_Value SetNamedProperty(JSVM_Env env, JSVM_CallbackInfo info) 424{ 425 // Obtain the parameter passed from JS. 426 size_t argc = 1; 427 JSVM_Value str; 428 char strKey[32] = ""; 429 OH_JSVM_GetCbInfo(env, info, &argc, &str, nullptr, nullptr); 430 // Obtain the string passed in and store it in strKey. 431 size_t keyLength; 432 OH_JSVM_GetValueStringUtf8(env, str, strKey, 32, &keyLength); 433 // Create an object. 434 JSVM_Value newObj; 435 OH_JSVM_CreateObject(env, &newObj); 436 // Set the property value to 1234. 437 int32_t value = 1234; 438 JSVM_Value numValue; 439 OH_JSVM_CreateInt32(env, value, &numValue); 440 // Associate the integer value with the property name. 441 JSVM_Status status = OH_JSVM_SetNamedProperty(env, newObj, strKey, numValue); 442 if (status != JSVM_OK) { 443 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_SetNamedProperty failed"); 444 return nullptr; 445 } else { 446 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_SetNamedProperty success"); 447 } 448 // Return the newly created object with the property set. 449 return newObj; 450} 451``` 452 453ArkTS code: 454 455```ts 456import hilog from "@ohos.hilog" 457// Import the native APIs. 458import napitest from "libentry.so" 459let script: string = ` 460 setNamedProperty("message") 461` 462try { 463 let result = napitest.runJsVm(script); 464 hilog.info(0x0000, 'testJSVM', 'Test JSVM setNamedProperty: %{public}s', result); 465} catch (error) { 466 hilog.error(0x0000, 'testJSVM', 'Test JSVM setNamedProperty error: %{public}s', error.message); 467} 468``` 469 470### OH_JSVM_GetNamedProperty 471 472Use **OH_JSVM_GetNamedProperty** to obtain the value of the specified property from a JS object. 473 474CPP code: 475 476```cpp 477// Register the GetNamedProperty callback. 478static JSVM_CallbackStruct param[] = { 479 {.data = nullptr, .callback = GetNamedProperty}, 480}; 481static JSVM_CallbackStruct *method = param; 482// Set a property descriptor named getNamedProperty and associate it with a callback. This allows the GetNamedProperty callback to be called from JS. 483static JSVM_PropertyDescriptor descriptor[] = { 484 {"getNamedProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 485}; 486// Define OH_JSVM_GetNamedProperty. 487static JSVM_Value GetNamedProperty(JSVM_Env env, JSVM_CallbackInfo info) 488{ 489 // Obtain the two parameters passed from JS. 490 size_t argc = 2; 491 JSVM_Value args[2] = {nullptr}; 492 char strKey[32] = ""; 493 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 494 // Obtain the name of the property to obtain. 495 size_t keyLength; 496 OH_JSVM_GetValueStringUtf8(env, args[1], strKey, 32, &keyLength); 497 // Obtain the value of the property and store it in result. 498 JSVM_Value result; 499 JSVM_Status status = OH_JSVM_GetNamedProperty(env, args[0], strKey, &result); 500 if (status != JSVM_OK) { 501 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_GetNamedProperty failed"); 502 return nullptr; 503 } else { 504 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_GetNamedProperty success"); 505 } 506 return result; 507} 508``` 509 510ArkTS code: 511 512```ts 513import hilog from "@ohos.hilog" 514// Import the native APIs. 515import napitest from "libentry.so" 516let script: string = ` 517 let obj = { data: 0, message: "hello world", 50: 1}; 518 getNamedProperty(obj, "message") 519` 520try { 521 let result = napitest.runJsVm(script); 522 hilog.info(0x0000, 'testJSVM', 'Test JSVM getNamedProperty: %{public}s', result); 523} catch (error) { 524 hilog.error(0x0000, 'testJSVM', 'Test JSVM getNamedProperty error: %{public}s', error.message); 525} 526``` 527 528### OH_JSVM_HasNamedProperty 529 530Use **OH_JSVM_HasNamedProperty** to check whether a JS object contains the specified property. 531 532CPP code: 533 534```cpp 535// Register the HasNamedProperty callback. 536static JSVM_CallbackStruct param[] = { 537 {.data = nullptr, .callback = HasNamedProperty}, 538}; 539static JSVM_CallbackStruct *method = param; 540// Set a property descriptor named hasNamedProperty and associate it with a callback. This allows the HasNamedProperty callback to be called from JS. 541static JSVM_PropertyDescriptor descriptor[] = { 542 {"hasNamedProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 543}; 544// Define OH_JSVM_HasNamedProperty. 545static JSVM_Value HasNamedProperty(JSVM_Env env, JSVM_CallbackInfo info) 546{ 547 // Obtain the two parameters passed from JS. 548 size_t argc = 2; 549 JSVM_Value args[2] = {nullptr}; 550 char strKey[32] = ""; 551 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 552 // Obtain the property name. 553 size_t keyLength; 554 OH_JSVM_GetValueStringUtf8(env, args[1], strKey, 32, &keyLength); 555 // Check whether the object has the specified property and store the result in hasProperty. 556 bool hasProperty = false; 557 JSVM_Status status = OH_JSVM_HasNamedProperty(env, args[0], strKey, &hasProperty); 558 if (status != JSVM_OK) { 559 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_HasNamedProperty failed"); 560 return nullptr; 561 } else { 562 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_HasNamedProperty success:%{public}d", hasProperty); 563 } 564 // Convert the bool value to JSVM_Value and return JSVM_Value. 565 JSVM_Value result; 566 OH_JSVM_GetBoolean(env, hasProperty, &result); 567 return result; 568} 569``` 570 571ArkTS code: 572 573```ts 574import hilog from "@ohos.hilog" 575// Import the native APIs. 576import napitest from "libentry.so" 577let script: string = ` 578 let obj = { data: 0, message: "hello world", 50: 1}; 579 hasNamedProperty(obj, "message") 580` 581try { 582 let result = napitest.runJsVm(script); 583 hilog.info(0x0000, 'testJSVM', 'Test JSVM hasNamedProperty: %{public}s', result); 584} catch (error) { 585 hilog.error(0x0000, 'testJSVM', 'Test JSVM hasNamedProperty error: %{public}s', error.message); 586} 587``` 588 589### OH_JSVM_DefineProperties 590 591Use **OH_JSVM_DefineProperties** to define properties for an object. 592 593CPP code: 594 595```cpp 596// Register the DefineProperties callback. 597static JSVM_CallbackStruct param[] = { 598 {.data = nullptr, .callback = DefineProperties}, 599}; 600static JSVM_CallbackStruct *method = param; 601// Set a property descriptor named defineProperties and associate it with a callback. This allows the DefineProperties callback to be called from JS. 602static JSVM_PropertyDescriptor descriptor[] = { 603 {"defineProperties", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 604}; 605// Define OH_JSVM_DefineProperties. 606static JSVM_Value DefineMethodPropertiesExample(JSVM_Env env, JSVM_CallbackInfo info) 607{ 608 int32_t propValue = 26; 609 JSVM_Value returnValue; 610 OH_JSVM_CreateInt32(env, propValue, &returnValue); 611 return returnValue; 612} 613 614// Define a callback for Getter. 615static JSVM_Value GetterCallback(JSVM_Env env, JSVM_CallbackInfo info) 616{ 617 JSVM_Value result; 618 const char *str = "Hello world!"; 619 size_t length = strlen(str); 620 // Create property values. 621 OH_JSVM_CreateStringUtf8(env, str, length, &result); 622 return result; 623} 624 625static JSVM_Value RunScriptAndLogResult(JSVM_Env env, const std::string &srcCode) { 626 JSVM_Value sourceCodeValue; 627 OH_JSVM_CreateStringUtf8(env, srcCode.c_str(), srcCode.size(), &sourceCodeValue); 628 JSVM_Script script; 629 // Compile the JS code string and return the compiled script. 630 OH_JSVM_CompileScript(env, sourceCodeValue, nullptr, 0, true, nullptr, &script); 631 JSVM_Value jsVmResult; 632 // Execute the JS script. 633 OH_JSVM_RunScript(env, script, &jsVmResult); 634 return jsVmResult; 635} 636 637static JSVM_Value DefineProperties(JSVM_Env env, JSVM_CallbackInfo info) { 638 // Obtain an empty object passed from JS. 639 size_t argc = 2; 640 JSVM_Value argv[2] = {nullptr}; 641 OH_JSVM_GetCbInfo(env, info, &argc, argv, nullptr, nullptr); 642 // Create a property value of the string type. 643 size_t length = 0; 644 OH_JSVM_GetValueStringUtf8(env, argv[1], nullptr, 0, &length); 645 char *buf = (char *)malloc(length + 1); 646 OH_JSVM_GetValueStringUtf8(env, argv[1], buf, length + 1, &length); 647 JSVM_Value stringValue; 648 OH_JSVM_CreateStringUtf8(env, "Hello!", JSVM_AUTO_LENGTH, &stringValue); 649 JSVM_CallbackStruct param[] = { 650 {.data = nullptr, .callback = DefineMethodPropertiesExample}, 651 {.data = nullptr, .callback = GetterCallback}, 652 653 }; 654 JSVM_PropertyDescriptor descriptor[] = { 655 // Define a property value of the method type. 656 {"defineMethodPropertiesExample", nullptr, ¶m[0], nullptr, nullptr, nullptr, JSVM_DEFAULT}, 657 // Define the property value of the string type. 658 {"defineStringPropertiesExample", nullptr, nullptr, nullptr, nullptr, stringValue, JSVM_DEFAULT}, 659 // Define the property value of the getter type. 660 {"getterCallback", nullptr, nullptr, ¶m[1], nullptr, nullptr,JSVM_DEFAULT}}; 661 // Create a property value of the method type. 662 // Define the defineMethodPropertiesExample function for the obj object and a variable in this function, and return it. 663 // When the obj object is called, this function can be invoked. 664 static std::string srcMethod; 665 JSVM_Status statusMethod; 666 statusMethod = OH_JSVM_DefineProperties(env, *argv, sizeof(descriptor) / sizeof(descriptor[0]), descriptor); 667 // Run obj.defineMethodPropertiesExample() and return the result to JS. 668 srcMethod = R"JS(obj.defineMethodPropertiesExample();)JS"; 669 JSVM_Value jsVmResult = RunScriptAndLogResult(env, srcMethod); 670 // Create a property value of the string type. 671 static std::string srcString; 672 JSVM_Status statusString; 673 statusString = OH_JSVM_DefineProperties(env, *argv, sizeof(descriptor) / sizeof(descriptor[1]), descriptor); 674 // Run obj.defineStringPropertiesExample() and return the result to JS. 675 srcString = R"JS(obj.defineStringPropertiesExample;)JS"; 676 JSVM_Value jsVmResult1 = RunScriptAndLogResult(env, srcString); 677 // Define a property with getter. 678 static std::string srcGetter; 679 JSVM_Status statusGetter; 680 statusGetter = OH_JSVM_DefineProperties(env, *argv, sizeof(descriptor) / sizeof(descriptor[2]), descriptor); 681 // Call getterCallback() of obj and return the result string to JS. 682 srcGetter = R"JS(obj.getterCallback;)JS"; 683 JSVM_Value jsVmResult2 = RunScriptAndLogResult(env, srcGetter); 684 if (statusMethod != JSVM_OK || statusString != JSVM_OK || statusGetter != JSVM_OK) { 685 OH_JSVM_ThrowError(env, nullptr, "JSVM DefineProperties fail"); 686 return nullptr; 687 } else if (statusMethod == JSVM_OK) { 688 int32_t number; 689 OH_JSVM_GetValueInt32(env, jsVmResult, &number); 690 OH_LOG_INFO(LOG_APP, "JSVM DefineMethodPropertiesExample success:%{public}d", number); 691 } else if (statusString == JSVM_OK) { 692 size_t length = 0; 693 OH_JSVM_GetValueStringUtf8(env, jsVmResult1, nullptr, 0, &length); 694 char *buf = (char *)malloc(length + 1); 695 OH_JSVM_GetValueStringUtf8(env, jsVmResult1, buf, length + 1, &length); 696 OH_LOG_INFO(LOG_APP, "JSVM defineStringPropertiesExample success:%{public}s", buf); 697 } else if (statusGetter == JSVM_OK) { 698 size_t length = 0; 699 OH_JSVM_GetValueStringUtf8(env, jsVmResult2, nullptr, 0, &length); 700 char *buf = (char *)malloc(length + 1); 701 OH_JSVM_GetValueStringUtf8(env, jsVmResult2, buf, length + 1, &length); 702 OH_LOG_INFO(LOG_APP, "JSVM getterCallback success:%{public}s", buf); 703 } 704 return jsVmResult; 705} 706``` 707 708ArkTS code: 709 710```ts 711import hilog from "@ohos.hilog" 712// Import the native APIs. 713import napitest from "libentry.so" 714// Define a property of the method type. 715let script: string = ` 716 let obj = {}; 717 defineProperties(obj) 718` 719let result = napitest.runJsVm(script); 720hilog.info(0x0000, 'testJSVM', 'Test JSVM defineGetterProperties: %{public}s', result); 721``` 722 723### OH_JSVM_GetAllPropertyNames 724 725Use **OH_JSVM_GetAllPropertyNames** to obtain the names of all available properties of a JS object as a JS array. 726 727CPP code: 728 729```cpp 730// Register the GetAllPropertyNames callback. 731static JSVM_CallbackStruct param[] = { 732 {.data = nullptr, .callback = GetAllPropertyNames}, 733}; 734static JSVM_CallbackStruct *method = param; 735// Set a property descriptor named getAllPropertyNames and associate it with a callback. This allows the GetAllPropertyNames callback to be called from JS. 736static JSVM_PropertyDescriptor descriptor[] = { 737 {"getAllPropertyNames", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 738}; 739// Define OH_JSVM_GetAllPropertyNames. 740static JSVM_Value GetAllPropertyNames(JSVM_Env env, JSVM_CallbackInfo info) 741{ 742 // Obtain the parameter passed from JS. 743 size_t argc = 1; 744 JSVM_Value args[1]; 745 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 746 // Obtain names of all properties (own properties) of the specified object. 747 JSVM_Value result; 748 JSVM_Status status = OH_JSVM_GetAllPropertyNames(env, args[0], 749 JSVM_KeyCollectionMode::JSVM_KEY_OWN_ONLY, 750 JSVM_KeyFilter::JSVM_KEY_WRITABLE, 751 JSVM_KeyConversion::JSVM_KEY_NUMBERS_TO_STRINGS, &result); 752 if (status != JSVM_OK) { 753 OH_JSVM_ThrowError(env, nullptr, "Failed to get allpropertynames"); 754 return nullptr; 755 } else { 756 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_GetAllPropertyNames success"); 757 } 758 return result; 759} 760``` 761 762ArkTS code: 763 764```ts 765import hilog from "@ohos.hilog" 766// Import the native APIs. 767import napitest from "libentry.so" 768let obj = '{ data: 0, message: "hello world", 50: 1}'; 769let script: string = ` 770 getAllPropertyNames(${obj}) 771 ` 772try { 773 let result = napitest.runJsVm(script); 774 hilog.info(0x0000, 'testJSVM', 'Test JSVM GetAllPropertyNames: %{public}s', result); 775} catch (error) { 776 hilog.error(0x0000, 'testJSVM', 'Test JSVM GetAllPropertyNames error: %{public}s', error.message); 777} 778``` 779