Get Current Tab URL From Chrome Extension in Go
source link: http://siongui.github.io/2018/02/02/tab-url-chrome-extension-in-go/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Get Current Tab URL From Chrome Extension in Go
February 02, 2018
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:
[2]How can I get the URL of the current tab from a Google Chrome extension? - Stack Overflow
[4]GitHub - fabioberger/chrome: GopherJS Bindings for Chrome
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK