Using C++ code in Browser? It's possible!
by QUBIT_MATRIX - Saturday January 4, 2025 at 07:50 AM
#1
Yo! I didn't even know that it was possible, so here's what I found out.

First you will need emscripten:
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
git pull
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh

To avoid running each time source ./emsdk_env.sh just add it to your shell profile.

When you've done that, you can start coding.

Set up a new index.html file like this:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebAssembly Example</title>
</head>
<body>
    <h1>Welcome to WebAssembly Example</h1>
    <p>This is a basic HTML structure for a WebAssembly project.</p>

    <p id="rand"></p>
    <script src="hello.js"></script>
<script>
  Module.onRuntimeInitialized = function() {
    Module._sayHello();
    var number = Module._getRandomNumber();
    console.log("Random number: " + number);
    document.getElementById("rand").innerHTML = "Random number: " + number;
  };
</script>

</body>
</html>

And a hello.cpp file:
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <emscripten.h>
#include <emscripten/bind.h>
#include <random>

extern "C" {
    void sayHello();
    int getRandomNumber();
}

EMSCRIPTEN_KEEPALIVE
void sayHello() {
    printf("Hello, WebAssembly!\n");
}

EMSCRIPTEN_KEEPALIVE
int getRandomNumber() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(1, 100);
    int random_number = dist(mt);
    printf("Random number: %d\n", random_number);
    return random_number;
}

Now to compile the code, you run: 
em++ hello.cpp -o hello.js -s WASM=1

After that start a http server using python: 
python -m http.server 80

Then open the website in browser: http://localhost

You can also check the developer console for output since printf(); logs to console.

Some more information - whenever you declare a function in your c++ code, you need to use EMSCRIPTEN_KEEPALIVE otherwise it would result in c++ name mangling.
Reply
#2
Thank you very much.
Reply
#3
I'll put it off, we'll figure it out after the holidays
Reply
#4
Here to remind you :3
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What browser do yall use? raspberryroot 32 1,212 02-22-2025, 02:30 AM
Last Post: Jayze
  The code that could change everything stucksnet 2 361 02-15-2025, 01:52 PM
Last Post: PomPomPurItInYourAss
  Spoofing HS256 Cupon Code Echo5Echo 0 215 01-24-2025, 09:59 PM
Last Post: Echo5Echo
  Get victim's browser fingerprints with info stealer TeaBlackPot 0 269 12-30-2024, 08:49 PM
Last Post: TeaBlackPot
  A browser alternative. boar 2 342 11-04-2024, 04:44 PM
Last Post: boar

Forum Jump:


 Users browsing this thread: