Calling JavaScript function from WebView in Cocos2d-x v3.3rc0

In this tutorial I am going to talk about calling JavaScript function from WebView in Cocos2d-x v3.3rc0. We are going to use our project called “ProjectName” which we created in our previous tutorial. To see our previous tutorial on how to create an application in Cocos2d-x, please click Here and to see how to create WebView in cocos2d-x application click Here.

So we are assuming you have a cocos2d-x project with WebView in it.

Open your project in Xcode. Open “index.html” file from “Resources” folder and paste the following code there. If you don’t have a “index.html” file under “Resources” folder then create it.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Calling JS from WebView</title>
</head>
<body>

<p>y = 5, z = 2, calculate x = y + z</p>

<p id="demo"></p>

<script>
function myFunction() {
    y = 5;
    z = 2;
    x = y + z;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

Open “HelloWorldScene.cpp” from “classes” directory. Include “ui/UIButton.h”. Add the following code at the end of “bool HelloWorld::init()” method before “return true;”.

cocos2d::ui::Button *evalJsBtn = cocos2d::ui::Button::create("CloseNormal.png", "CloseSelected.png");
evalJsBtn->setTitleText("");
evalJsBtn->setPosition(Vec2(winSize/2) - Vec2( webView->getContentSize().width/2 + evalJsBtn->getContentSize().width/2 + 10,-50 ));
evalJsBtn->addClickEventListener([=](Ref*){ 
    webView->evaluateJS("myFunction()");
});

this->addChild(evalJsBtn);

On the code above we created a button using C++ code and used “evaluateJS()” method to call our JavaScript function “myFunction()” from “index.html”.

Now run the application and you will see a button on the middle left of your emulator outside the WebView. Once you click it you can see the output of our function named “myFunction()” inside the WebView.

This is how you can call a JavaScript function from WebView in Cocos2d-x v3.3rc0. If you have any questions feel free to ask me in the comment section.

About MD Mosleh Uddin

Trying to create an interesting and comfortable environment for the beginners of different programming languages and web design.

One thought on “Calling JavaScript function from WebView in Cocos2d-x v3.3rc0”

Leave a Reply

Your email address will not be published. Required fields are marked *

four × one =