Youtube Chrome Extension That Labels Upload Dates?

In this article, nosotros'll develop a chrome extension using which the user tin create bookmarks corresponding to different timestamps, shop them somewhere(for now in chrome local storage), and retrieve the bookmarks(stored every bit timestamped youtube video links).

The code is hosted here: GitHub. The video explainer for the chief extension can be constitute here(in the principal extension's repo). Note that the project is still a Work in Progress at the time of writing this commodity.

Allow'south get started. Broadly speaking, we'll divide this article into 3 parts. In the first part, nosotros'll claw up the extension and so that we can admission our in-development extension in Chrome. In the second function, we'll take a look at a basic extension and talk almost the code and the compages. In the 3rd part, we'll develop the main extension.

one. Testing our extension during development

To exam and debug our extension during the development phase, we'll follow the below steps to get a basic extension up and running.

  1. Create the manifest.json file and the project construction as shown above or download them from the link at the top of the article.
  2. Become to chrome://extensions from your browser. <ss here>
  3. Toggle the 'Developer Manner' to ON.
  4. Click on the 'Load Unpacked' pick to load the Extension folder for test, debug and further development.
  5. At this point, you should see your Extension on the right side of the address bar of the chrome.

Browser screen snippet to show diverse options used to ready a functioning extension

Now that we accept loaded our Extension folder on chrome, nosotros are set up to build a basic chrome extension and examination it out.

2. Basic Chrome Extension – Hi, there!

We'll build an extension that will say, "Hi, there!" when the user clicks on the Extension icon. The code tin can be found here.

Clicking the 'H' icon opens the popup.html with a Hi, there! message

For that, we'll need the following files.

  • manifest.json – To concord information about the Chrome extension.
  • popup.html – To say, "Hi, at that place!" when the user clicks on the extension icon.
  • popup.js – No significant work of this file at this betoken. Although, nosotros'll keep it here.
  • background.js – To load upwardly the extension with the basic backend functionality. Non required for the Hi, at that place! Extension.
  • jQuery.js – Nosotros'll include jQuery to help with development.

1. manifest.json file

{ "name": "Hi, there! Extension", "version": "1.0", "description": "I greet", "permissions": ["activeTab"], "options_page": "options.html", "groundwork": { "scripts": ["background.js"], "persistent": false }, "browser_action": { "default_popup": "popup.html", "default_title": "Hi, there Extension" }, "manifest_version": 2 }        

Allow's await at the key-value pairs in the manifest.json file in more than detail.

  1. name – This is the name of the extension. In the browser screen snapshot, you tin see this equally 'Hi, at that place! Extension.
  2. version – This is the version of the extension. Information technology'south taken equally 1.0 because when we upload it for review to the chrome web store, information technology would exist one.0 initially. In the evolution phase, you may name it as 0.0, and then 0.1, and then on as well.
  3. description – Description of the extension. Information technology's a good practise to keep it concise.
  4. permissions – The permissions key-value pair holds the different permission that the Extension requires access to work properly. The value is an array of strings. The elements of the array can be either known strings, or a pattern lucifer(usually used to match web addresses). For example, https://youtube.com/* -> gives permission to the extension for all links with domain proper noun youtube.com. Here, the '*' is a wildcard pattern. Besides, note that some of the permissions declared here may demand the user's explicit blessing also. You tin can read more than about permissions in the official docs.
  5. options_page – The options page is used to give a user more options. The user tin access the options folio by either right-clicking on the extension and click on the 'options' push button from the carte, or going to the options folio from the 'chrome://extensions' page. The setting used in the above manifest will cause the options.html page to open in a new tab. It is besides possible to open the 'options' page in the same tab in an embedded mode. In the basic 'Hi, there!' extension, we don't demand this pick. Yous tin read more than nearly the 'options' in the official docs. perhaps add together more here
  6. groundwork – background script(due south) is declared here. The background script is used to listen to events and react to them, as the extension is an event-driven image. A background page is loaded when information technology is needed and unloaded when it goes idle, i.e., the groundwork script volition keep running while it is performing an activeness and unload later on the action is performed. In our 'Hi, there!' extension, we haven't used the groundwork script functionality. You can also detect that the "persistent" cardinal is set to imitation because it's the standard practice, and as mentioned in the docs, the just time nosotros should set "persistent" to true is when the extension is using the chrome.webRequest API to block or alter network requests, which we're not doing.
  7. browser_action – The browser_action is used by the Extension to put the icon on the correct side of the chrome's address bar. The extension and then listens for clicks, and when the icon is clicked, it does something. In our case, it opens the popup.html folio containing the Hi, there! greeting. The 'default_title' field value is a string that is displayed when the user hovers over the extension's icon.
  8. manifest_version – At the time of writing this article, developers are being encouraged to endeavour out the before longhoped-for-launched manifest_version iii. Still, version 2 is even so available and familiar, so nosotros'll apply version 2. For version 3, you can start here.

2. popup.html file

HTML

<!DOCTYPE html>

< html >

< head ></ head >

< body >

< h5 >Hello, there!</ h5 >

< script src = "jquery-3.5.ane.js" >

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

</ script >

</ body >

</ html >

How does the Bones Chrome Extension work?

Later on nosotros've 'load unpacked' the chrome extension, the manifest.json file is candy. Later this, the 'groundwork' is run to initialize the extension and for listening to other events. Now, that we've got an understanding of chrome extension from the evolution point of view, we'll look at the main Extension that nosotros want to build – YouTube Bookmarker Extension.

Main Extension – YouTube Bookmarker

The video demo for the YouTube Bookmarker extension can be institute here.

Features of the Extension:

  • Works on youtube.com tabs in a Chrome extension to bookmarks points in videos.
  • When the user clicks on the <input> tag in the popup.html window, the extension takes note of the timestamp at which the <input> tag was 'on focus'. After taking the input from <input> tag as well, it appends it in the 'bookmarked points' department of popup.html, as seen in the explainer video.

Project Directory structure:

projection directory structure

Source Code:

1. As the extension would access and store the web addresses, i.e., youtube video addresses, it becomes imperative to accept a expect at the unlike kinds of timestamps that nosotros tin access from the DOM.

If 1 runs

var result1 = certificate.querySelector('#movie_player > div.ytp-chrome-bottom > div.ytp-progress-bar-container > div.ytp-progress-bar').getAttribute("aria-valuetext");

It will give the timestamp in word format, as defined below. You are beingness encouraged to run the above query selector in the chrome's window console attainable by pressing 'Ctrl+Shift+J'.

The below are the types of timestamps that can be retrieved in word format past running the query selector above.

ane Hours 48 Minutes 31 Seconds of ii Hours 56 Minutes 33 Seconds //for video greater than one hours long and the electric current //timestamp beingness greater than i hour too.   -> 0 Minutes 46 Seconds of 2 Hours 56 Minutes 33 Seconds //for video greater than ane hours long and //electric current timestamp < 1 minute  -> viii Minutes 33 Seconds of 2 Hours 56 Minutes 33 Seconds //for video greater than i hours long and //current timestamp >= 1 minute and less than i hr  -> 0 Minutes 0 Seconds of 0 Minutes 56 Seconds //for video less than one infinitesimal long and //current timestamp < 1 minute

2. manifest.json:

{ "name": "Youtube video bookmarker", "version": "1.0", "clarification": "An extension that bookmarks time points in youtube video", "permissions": ["activeTab", "declarativeContent",          "storage", "tabs", "https://world wide web.youtube.com/*"], "options_page": "options.html", "background": { "scripts": ["background.js"], "persistent": false }, "externally_connectable": { "matches": ["*://*.youtube.com/*"] }, "browser_action": { "default_popup": "popup.html", "default_title": "YouTube Video Bookmarker - GFG" }, "manifest_version": 2 }        

The fields of manifest.json file are defined beneath:

  • name, version, description, browser_action. manifest_version, options_page, – Already covered in adequate detail in the previous await at manifest.json
  • permissions – An array of strings.
    • activeTab – Have admission to the active tab
    • storage – Accept access to storage APIs of chrome.
    • https://youtube.com/* – pattern-based hostname to which the admission if required for manipulation and working of extension
    • tabs – Have access to 'tabs' API.
    • declarativeContent – To take deportment depending on the content of the current page.

3. popup.html:

HTML

<!DOCTYPE html>

< html >

< caput ></ head >

< torso >

< div >

< div id = "bookmarktakerdiv" >

< h5 style = "colour:darkgreen" >Youtube video Bookmarker</ h5 >

< bridge id = "currts" >xx:20</ span >

< span id = "receiptts" mode = "color:darkgreen" ></ span >

< input blazon = "text" id = "bookmarkdesc" />

< push button id = "submitbookmark" type = "button" >Bookmark</ button >

</ div >

< 60 minutes />< div id = "bookmarklistdiv" >

< p >Bookmarked points</ p >

< ul id = "bookmark_ulist" >

</ ul ></ div >

</ div >

< script src = "jquery-3.five.i.js" ></ script >

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

</ trunk ></ html >

Here nosotros take the implementation of the popup.html file:

  • We have ii <div> tag.
    • #bookmarktakerdiv – Takes bookmark and timestamp as input from the user.
    • #bookmarklistdiv – Holds an unordered listing of bookmarks taken already for the electric current video. The 'current video' here refers to the video currently being played on the tab currently agile.
  • We have 1 <ul> ( #bookmark_ulist) which holds the hyperlinked bookmarks and their timestamp.

4. popup.js:

Javascript

'employ strict' ;

$( function () {

})

$( '#bookmarkdesc' ).focus( function () {

console.log( 'focus bookmark description input field' )

chrome.runtime.sendMessage({ method: "gettimestampforcurrentpoint" });

chrome.runtime.onMessage.addListener(tsvalue);

var ts, tslink;

part tsvalue(msg) {

if (msg.method == "tsfind" ) {

ts = msg.tsvaltopopup;

tslink = msg.fl;

$( '#submitbookmark' ).on( 'click' , role () {

var bookmarkinput = $( '#bookmarkdesc' ).val();

$( '#bookmark_ulist' ).suspend( '<li><span>' + ts +

' - <a href="' + tslink + '">' +

bookmarkinput +

'</a></span></li>' );

panel.log( 'list item appended to bookmark_ulist' )

});

$( '#currts' ).text(msg.tsvaltopopup)

$( '#receiptts' ).text( 'got timestamp' )

}

}

})

The beneath list explains the approach we took for popup.js:

  • When the user clicks on the <input> tag uniquely identified by id 'bookmarkdesc', the event is fired with { method: "gettimestampforcurrentpoint" } object. This outcome is captured by background.js equally we'll see later.
  • Function tsvalue() is fired from the background.js to transfer video information from the browser window frame to the extension window frame.
  • Inside the tsvalue() function, the click event on '#submitbookmark' button appends the <li> element containing the timestamp and the bookmark hyperlinked by timestamped YouTube video link to the #bookmark_ulist in popup.html.
  • So, to explicate again, after the user clicks on the extension icon, if the video is a YouTube video in the main browser window frame, the timestamp and bookmark are built into an <li> element which is appended to the <ul> in popup.html.
  • As you can note, popup.js adds interactivity to popup.html and communicated with groundwork.js using an event-driven paradigm.

v. groundwork.js

Javascript

"use strict" ;

chrome.runtime.onMessage.addListener(checktimestamp);

office checktimestamp(msg) {

if (msg.method == "gettimestampforcurrentpoint" ) {

panel.log( "bg.js gettimestampforcurrrentpoint called" );

chrome.tabs.executeScript( null , { file: "./gettimestamp.js" }, () => {

console.log( "injected gettimestamp.js file into YT window DOM." );

});

}

}

chrome.tabs.onActivated.addListener((tab) => {

console.log(tab);

chrome.tabs.get(tab.tabId, (c) => {

if (/^https:\/\/www\.youtube/.exam(c.url)) {

chrome.tabs.executeScript( null , { file: "./foreground.js" }, () => {

console.log( "i injected fg using bg script in youtube webpages" );

});

}

});

});

chrome.runtime.onMessage.addListener(getcurrenttimestamp);

function getcurrenttimestamp(msg) {

if (msg.method == "sendtimestamptobg" ) {

var temp1 = msg.tsvalue;

var temp2 = msg.finallink;

panel.log( "msg.tsvalue value: " + msg.tsval);

console.log( "msg.finallink " + msg.finallink);

chrome.runtime.sendMessage({

method: "tsfind" ,

tsvaltopopup: temp1,

fl: temp2,

});

}

}

chrome.runtime.onMessage.addListener(localstorageset);

role localstorageset(msg) {

if (msg.method == "setlocalstorage" ) {

console.log( "setlocalstorage groundwork.js" );

}

}

Let's check out what we did in the background.js file:

  • When the user clicks on the <input> field to brand a bookmark, in the background script, checktimestamp() function is chosen which injects the gettimestamp.js script into the window of the browser. As the file proper name suggests, it volition requite us the current timestamp and the timestamped YouTube video link, which nosotros'll mind to using an eventListener getcurrenttimestamp.
  • The function getcurrenttimestamp volition send the timestamp(in seconds) and the timestamped video link to popup.js(the extension's context/frame) after receiving it from an event which is fired with an object belongings {msg.method = 'sendtimestamptobg'}. This result listens to a message sent from gettimestamp.js script.

6. gettimestamp.js

Javascript

var result1 = certificate

.querySelector(

"#movie_player > div.ytp-chrome-bottom >div.ytp-progress-bar-container >div.ytp-progress-bar"

)

.getAttribute( "aria-valuetext" );

var temparr = result1.split( " " );

var tshhmmss_string;

if (temparr[6] == "Hours" ) {

tshhmmss_string = + "00:" + temparr[0] + ":" + temparr[ii];

} else if (temparr[1] == "Hours" ) {

tshhmmss_string = temparr[0] + ":" + temparr[2] + ":" + temparr[4];

} else if (temparr[6] == "Minutes" ) {

tshhmmss_string = "00:" + temparr[0] + ":" + temparr[2];

}

panel.log( "gettimestamp.js " + result1);

var windowlink = window.location.href;

console.log( "gettimestamp.js windowlink " + windowlink);

var idx = windowlink.indexOf( "v=" );

console.log( "gettimestamp.js idx value " + idx);

function getseconds(timestamphhmmss) {

var ten = timestamphhmmss.split( ":" );

var seconds = parseInt(x[0]) * lx * lx + parseInt(x[ane]) * sixty + parseInt(x[ii]);

console.log( "seconds calculated gettimestamp.js getinseconds" + seconds);

return seconds;

}

var timeinseconds = getseconds(tshhmmss_string);

var windowlinkfinal;

if (idx == -1) {

} else {

windowlinkfinal =

windowlink.substr(idx + 2, 11) +

"&t=" +

timeinseconds;

console.log( "gettimestamp.js windowlinkfinal " + windowlinkfinal);

}

chrome.runtime.sendMessage({

method: "sendtimestamptobg" ,

tsvalue: tshhmmss_string,

finallink: windowlinkfinal,

});

Let's check out what we did in the gettimestamp.js file above:

  • gettimestamp.js script runs in the browser frame/context. This script uses the querySelector to excerpt the timestamp in word format, converts it into hh:mm:ss format and in seconds.
  • Information technology also takes the current video link and converts it into a generic format.

The timestamp in hh:mm:ss format and the timestamped video link are emitted for consumption past background.js file. The event is identified by 'method: "sendtimestamptobg"' cardinal.

Further Development Scope for you to endeavour out

Feel costless to raise a PR or effect on the repo. The immediate WIP is connecting it to chrome.localStorage.

  • Connect the extension to a local database or Firebase for decoupled data storage.
  • Data structure research and implementation while storing the data.
  • Disconnecting from Chrome's local storage, and using 'sync storage' so that the bookmarks are available on other devices besides
  • Better the UI/UX of the extension
  • Pattern the icons and store them in the project directory for custom extension icons

elliottwhatelto.blogspot.com

Source: https://www.geeksforgeeks.org/chrome-extension-youtube-bookmarker/

0 Response to "Youtube Chrome Extension That Labels Upload Dates?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel