In [ ]:
target_name_in_kernel <- "kernel_target"
target_name_in_browser <- "browser_target"
library(IRdisplay)
library(IRkernel)
comm_manager <- get("comm_manager", envir = as.environment("package:IRkernel"))()

Open handler in the kernel


In [ ]:
target_handler <- function(comm, data){
    print("Got open call")
    print( data )
    
    comm$on_msg(function(msg){
        print("Got message")
        print(msg)
    })
    
    comm$on_close(function(){
        print("Got close")
    })
}

comm_manager$register_target(target_name_in_kernel, target_handler)

Test in Javascript console


In [ ]:
display_javascript(sprintf('
const comm = IPython.notebook.kernel.comm_manager.new_comm("%s",{list:[1,2,3,4,5,6,7,8,9]})

comm.send({foo:"bar"})

comm.close()
', target_name_in_kernel))

Open handler in browser

Register target in browser


In [ ]:
display_javascript(sprintf('
IPython.notebook.kernel.comm_manager.register_target("%s", function() { 
    console.log("Got open message", arguments) 
})', target_name_in_browser))

In [ ]:
comm <- comm_manager$new_comm(target_name_in_browser)
comm$open()

Need to get a handle on the comm object in the browser.
Put a breakpoint in comm.js in CommManager.prototype.comm_open and run window.testcomm = comm

Register on_msg and on_close:

  • window.testcomm.on_msg(function(data){console.log("Got data", data)})
  • window.testcomm.on_close(function(data){console.log("Got close", data)})

In [ ]:
comm$send()

In [ ]:
comm$close()