Octopi
Posted on 25 November 2019 in dev
I read quite a lot of notebooks and html files (outputs of notebooks) on Github. An issue I often encountered was that depending on the file size (bigger than > 1Mb) Github couldn't sometimes display them.
There is a trick to overcome that, you have to use a specific website to get the preview you want. It's annoying. I don't want to have to copy paste the url of the notebook or HTML, sometimes tweak a bit the url and then finally you get what you want.
Solution
It didn't take too much thinking to solve my problem. I would like to be able to preview in one click the file I want: get the url, have a script do some processing if needed and then redirect me to the right website:
- HTML preview: https://htmlpreview.github.io/
- Notebook preview: https://nbviewer.jupyter.org/
Based on my first Chrome extension, I developed Octopi. The meat of the extension is contained in this js script.
Code
function get_html(menu) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true, 'currentWindow': true}, function (tabs) {
var giturl = tabs[0].url;
if (menu.menuItemId == 'html') {
chrome.tabs.create({
url: "https://htmlpreview.github.io/?"+giturl
});
} else if (menu.menuItemId == 'notebook') {
var res = giturl.split("github.com/");
chrome.tabs.create({
url: "https://nbviewer.jupyter.org/github/"+res[1]
});
}
});
}
chrome.contextMenus.create({
id: "html",
title: "Open HTML",
contexts:["all"],
onclick: get_html
});
chrome.contextMenus.create({
id: "notebook",
title: "Open notebook",
contexts:["all"],
onclick: get_html
});
Tadaaaa! Nothing really difficult here but I struggled a bit with debugging. I wanted to check if I got the right url before
jumping to another tab, making the process quicker to debug. No matter how I would display the url in the console.log
, nothing
got displayed. alert
was working fine but not console.log
. After searching for a bit, I came to realize that the issue comes from
using console.log
within a Chrome extension.
A few stackoverflow answers later, I could display what I wanted. Log messages don't appear with the webpage you are trying to process but in the background page your extension lives in. Once you access that page (through the developer mode > details of the extension > inspect views > background page), you can look at the console and then everything you log through the extension is there.
Conclusion
As usual developing a Chrome extension is quite simple as long as you do simple processing. The documentation for Chrome extensions is not that clear, sometimes handwaving (e.g. contexts
) and I wish it was more straightforward.
Reference
- https://stackoverflow.com/questions/10257301/where-to-read-console-messages-from-background-js-in-a-chrome-extension