Get Current Tab URL From Chrome Extension in Go


Build Chrome Extension with Go, compiled to JavaScript via GopherJS. This post shows you how to use Go to build Chrome extension that gets the URL of current active tab.

Besides GopherJS, you need the following packages to build extension:

Install the packages:

$ go get -u github.com/gopherjs/gopherjs
$ go get -u github.com/fabioberger/chrome
$ go get -u github.com/siongui/godom

To build the extension, we need three files: manifest.json, popup.go, popup.html. We will explain one by one.


manifest.json:

{
  "manifest_version": 2,

  "name": "tab url",
  "description": "print url of current active tab",
  "version": "0.1",

  "browser_action": {
    "default_title": "tab url",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs"
  ]
}

This manifest json tells Chrome the information of our extension.

The above manifest says that when users click on the icon of our extension, a popup window will show up. We need the tabs permission to access the information of Chrome tabs.


popup.html:

<script src="popup.js"></script>

This HTML file contains nothing except including JavaScript file. We will print the tab URL here via document.write method.


popup.go: compiled to popup.js via GopherJS.

package main

import (
      "github.com/fabioberger/chrome"
      . "github.com/siongui/godom"
)

func main() {
      c := chrome.NewChrome()
      queryInfo := chrome.Object{
              "active":        true,
              "currentWindow": true,
      }
      c.Tabs.Query(queryInfo, func(tabs []chrome.Tab) {
              tab := tabs[0]
              Document.Write(tab.Url)
      })
}

The above code gets the current active tab, and then print the URL of the tab via document.write method.

The above Go code is equivalent to the following JavaScript code:

chrome.tabs.query({'active': true, 'currentWindow': true}, function (tabs) {
    var tab = tabs[0];
    document.write(tab.url);
});

The full code example, including JavaScript counterpart, of this post is on my GitHub.


References:

[1]
[2]How can I get the URL of the current tab from a Google Chrome extension? - Stack Overflow
[3]GopherJS - A compiler from Go to JavaScript (GopherJS Playground, godoc)
[4]GitHub - fabioberger/chrome: GopherJS Bindings for Chrome
[5]GitHub - siongui/godom: Make DOM manipultation in Go as similar to JavaScript as possible. (via GopherJS)