Executing a JavaScript function from V8 in C++: A Step-by-Step Guide

When I want to run a basic Javascript program using v8, I follow these steps:

// Define a string containing the JavaScript source code.
v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, "'Hello' + ', from Javascript!'", v8::NewStringType::kNormal).ToLocalChecked();

// Compile the provided source code.
v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalChecked();

// Execute the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();

If I want to call a Javascript function in /path/to/my_js_functions.js file, how can I achieve this?

function myJsFunction(stringParam) {
  return stringParam   // The function simply returns the input parameter
}  

I appreciate any guidance. Thank you!

Answer №1

To start, you need to obtain the function object. Assuming it resides in the global scope (meaning it's on the global object), you can access it like this:

v8::Local<v8::String> name = v8::String::NewFromUtf8(
    isolate, "myJsFunction", v8::NewStringType::kInternalized).ToLocalChecked();
v8::Local<v8::Value> obj =
    context->Global()->Get(context.local(), name).ToLocalChecked();
if (!obj->IsFunction()) {
  /* Handle error if someone overwrote it */
}
v8::Local<v8::Function> my_function = v8::Local<v8::Function>::Cast(obj);

Keep in mind that whenever you receive a MaybeLocal, the result may be empty if an exception was thrown. If there's no guarantee against exceptions, avoid using just .ToLocalChecked() (as it will crash when the MaybeLocal is empty) and properly account for and manage the error scenario.

Once you have the function, you can prepare arguments for it and invoke it:

v8::Local<v8::Value> receiver = ...;
int argc = ...;
v8::Local<v8::Value> args[argc] = ...;
v8::MaybeLocal<v8::Value> result = my_function->Call(context.local(), receiver, argc, args);

Again, the result comes as a MaybeLocal because functions can throw exceptions (either explicitly or indirectly through other calls/actions). It's your responsibility to handle any errors and then appropriately convert the result to its intended type for further processing.

(Interacting with JavaScript via a C++ API can be challenging due to the significant conceptual differences between the two languages.)

For more examples, refer to V8's test-api.cc.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to utilize the Put method with Ajax, but the script does not seem to be executing

Currently, I am working on implementing the Put method using Ajax: <!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></ ...

Navigating a Mesh in 3D Space using three.js, Camera Movement, and physi.js

I am attempting to manipulate an object in Three.js using Physi.js. The camera is linked to the moving mesh, and I am moving it using .setLinearVelocity(); Additionally, I rotate it using .setAngularVelocity(); However, the issue I am facing is that whil ...

Is there a way to send an array of objects using axios-http?

Currently, I am utilizing react-dropzone for uploading mp3 files and a metadata npm to extract all the file contents. However, upon sending it to axios.post(), an error is encountered stating "Body Exceeded 1mb limit" Here is the snippet where the new dat ...

Challenges with implementing a code for achieving a small straight in a Yahtzee game

For a school assignment, I am struggling to understand how to calculate a small straight for the game of yahtzee. I have successfully coded for all other possible rolls except this one. Despite searching extensively, I have not been able to find a simple ...

Using `preventDefault()` will also block any text input from being entered

Note: I am looking for a way to clear the text box using the enter key after typing some text. My apologies for any confusion caused. Update 2: The missing event parameter was causing all the issues. I feel like a failure as a programmer. I am trying to ...

Executing a function with a click, then undoing it with a second click

My goal is to trigger an animation that involves text sliding off the screen only when the burger icon is clicked, rather than loading immediately upon refreshing the page. The desired behavior includes activating the function on the initial click and then ...

Can the pointer to a dynamically allocated array be duplicated before memory is allocated for it?

Apologies if this question has been raised previously, as I have not found the answer yet. I was surprised that the code below does not output "300" as expected: #include <iostream> int main() { int *array; int *arrayCopy = array; array = n ...

Catching the elusive culprit: How to snag the value responsible for an

Is there a method to access the specific value that triggered an exception to be thrown? Currently, I am utilizing a Nest global exception filter that catches a wide range of exceptions (a simple one similar to the example provided in Nest's documenta ...

Guide on utilizing the eval() function to assign a value to a field passed as a parameter

I am interested in achieving the following: function modifyField(fieldName){ eval(fieldName) = 1234; } In simpler terms, I want to pass a specific field name as a parameter and then assign a value to that field. Can someone guide me on how to accomp ...

Utilizing Raycaster for modifying the Box's face color upon clicking

I've been experimenting with the raycaster in order to select faces of cubes that are created, and then change the color of the clicked face. So far, I've managed to make it work for selecting entire objects, but not individual faces of those obj ...

There seems to be a glitch with the functionality of the HighStocks Tooltip

I've implemented a modified version of the example from highcharts: $(function () { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) { // Create the chart $('#co ...

When trying to access localhost:5000, the index.js file is unable to retrieve /

const NutritionAPI = require('./nutritionapi'); const nutService = new NutritionAPI('50cee42503b74b4693e3dc6fccff8725','2755697297a84ac5a702461b166e71f6'); // Setting up Express webhook const express = require('express&ap ...

Create data structures in python, php, c#, go, c++, and java using a JavaScript/JSON object

I am looking for a way to reverse the output of the JSON.stringify function specifically for node.js. My goal is to generate code snippets for various programming languages by converting JavaScript structures into their native counterparts in python, PHP, ...

For each individual category in the mongoose database, conduct a search

Seeking assistance with mongoose scope issue User.findById(req.user.id, (err, result) => { var cartProduct = []; result.cart.map(async (item) => { //item represents the following object: productId: "product-id", quan ...

Utilizing Webpack for Effortless Image Loading in Angular HTML

I've been struggling with webpack and angular configuration. It seems like a simple issue, but I just can't seem to find the solution. Despite scouring Stack Overflow for answers, I'm still stuck. My HTML page looks like this (along with ot ...

Utilize JavaScript to iterate through a JSON object and retrieve the indices that meet the specified criteria

While I found a previous answer that somewhat addresses my issue, I am seeking guidance on how to return an array of the indexes where a specific value appears. For example, if **18A38** is the target value, it should return the positions [1,3]. The sampl ...

Ag-Grid: Matching colors with filtering functionality

Can AG-Grid be configured to highlight matching cells during quick filtering? For example, if I have the following data: [ { firstName: 'Tom', lastName: 'Doe', company: 'Tesla' }, { firstName: 'Tim', lastName: & ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Tips for enhancing the color saturations of cells that overlap in an HTML table

My goal is to enhance the color of overlapping cells in my HTML tables. For instance, when I click on cell 2, the .nextAll(':lt(5)') method will change the class of the next 4 cells. https://i.stack.imgur.com/mwv8x.png Next, clicking on cell 3 ...

Streaming videos using Flask with a custom template

After successfully implementing the DWA path planning algorithm in C with Python bindings, I have decided to create a web application demo. The concept involves a "robot" following the mouse using DWA, while allowing users to draw walls for objects. My ini ...