1+
2+ const countApi = 'https://greasyfork.org/scripts/by-site.json'
3+
4+ function getCurrentTabUrl ( callback ) {
5+ // Query filter to be passed to chrome.tabs.query - see
6+ // https://developer.chrome.com/extensions/tabs#method-query
7+ var queryInfo = {
8+ active : true ,
9+ currentWindow : true
10+ } ;
11+
12+ chrome . tabs . query ( queryInfo , ( tabs ) => {
13+ // chrome.tabs.query invokes the callback with a list of tabs that match the
14+ // query. When the popup is opened, there is certainly a window and at least
15+ // one tab, so we can safely assume that |tabs| is a non-empty array.
16+ // A window can only have one active tab at a time, so the array consists of
17+ // exactly one tab.
18+ var tab = tabs [ 0 ] ;
19+
20+ // A tab is a plain object that provides information about the tab.
21+ // See https://developer.chrome.com/extensions/tabs#type-Tab
22+ var url = tab . url ;
23+
24+ // tab.url is only available if the "activeTab" permission is declared.
25+ // If you want to see the URL of other tabs (e.g. after removing active:true
26+ // from |queryInfo|), then the "tabs" permission is required to see their
27+ // "url" properties.
28+ console . assert ( typeof url == 'string' , 'tab.url should be a string' ) ;
29+
30+ callback ( url ) ;
31+ } ) ;
32+
33+ // Most methods of the Chrome extension APIs are asynchronous. This means that
34+ // you CANNOT do something like this:
35+ //
36+ // var url;
37+ // chrome.tabs.query(queryInfo, (tabs) => {
38+ // url = tabs[0].url;
39+ // });
40+ // alert(url); // Shows "undefined", because chrome.tabs.query is async.
41+ }
42+
43+ function getUrlHost ( url ) {
44+ let a = document . createElement ( 'a' ) ;
45+ a . href = url ;
46+ let mainHost = psl . get ( a . hostname ) || a . hostname . split ( '.' ) . splice ( - 2 ) . join ( '.' )
47+ return mainHost
48+ }
49+
50+ function changeBadge ( data ) {
51+ getCurrentTabUrl ( function ( url ) {
52+ let host = getUrlHost ( url )
53+ let count = data [ host ]
54+ count = count > 50 ? 50 : count
55+ sessionStorage . setItem ( 'host' , host )
56+ if ( count ) {
57+ chrome . browserAction . setBadgeText ( {
58+ text : count . toString ( )
59+ } )
60+ } else {
61+ chrome . browserAction . setBadgeText ( {
62+ text : ''
63+ } )
64+ }
65+ } )
66+ }
67+
68+ fetch ( countApi ) . then ( ( r ) => {
69+ r . json ( ) . then ( ( data ) => {
70+ console . log ( 'count data loaded!' )
71+ chrome . tabs . onUpdated . addListener ( ( ) => {
72+ changeBadge ( data )
73+ } )
74+ chrome . tabs . onActivated . addListener ( ( ) => {
75+ changeBadge ( data )
76+ } )
77+ } )
78+ } )
0 commit comments