rtnF

PeerJS

So, several month ago, I made my own notetaking app. Markdown support, autosave, saved locally inside the browser's IndexedDB.

Later, i need a sync feature, so i can transfer my notes from my phone to my PC easily.

My first approach? Quite naive. Just upload the local notes into a centralized server. Good, working, but it's quite costly (I have to cover its monthly server cost) and there's quite a privacy issue (I technically can read everyone's note).

Is there any alternative?

Then, I tried PeerJS. The idea is simple : send the data from phone to PC directly by using P2P protocol.


It's done. Here's the procedure.

First, setup the receiving device. Open "recv.html" (https://altilunium.github.io/md/recv.html), then set the p2p key. This key must be globally unique, so if there's a duplicate error, you have to refresh the page and pick another key.

Then, prepare to send the data. Open your notes (https://altilunium.github.io/md/), click the p2p-upload button (middle), then enter the p2p key that we created on first step.

Done, your notes will be copied to your recv.html.


Here's the recv.html source code :

var pro = prompt("Input p2p key")
var p2p_key = "cpad_receiver_" + pro
var peer = new Peer(p2p_key);

peer.on('error', function(err){
  console.log(err)
  alert(err)
})

// Display P2P key on the screen
peer.on('open',function(e){
  alert("Connection successful!")
  var keyh1 = document.getElementById("not")
  keyh1.innerHTML = pro
})

// Data received. Show it on the screen
peer.on('connection', function(conn) {
  conn.on('data', function(data){
    var nyo = document.getElementById("main-txtbox")
    nyo.innerHTML = data
  });
});

Here's the p2p-upload button source code :

var peer = new Peer();
async function publish_p2p() {
  var pro = prompt("Input p2p key")
  var p2p_key = "cpad_receiver_" + pro
  conn = peer.connect(p2p_key);
  conn.on('open', function(){
    var payload = document.getElementById("main-txtbox")
    conn.send(payload.innerHTML);
    alert("Successful!")
})
}

Quick and simple.


At this point, I'm using free PeerJS's PeerServer connection broker. If their server is down, then this functionality will also down as well.

For reliability reasons, maybe I should set-up my own PeerServer instance later.