Refactored code to allow code reuse for future

Extracted functionality from the contextmenu onclick method to a separate function to allow code reuse in future.
This commit is contained in:
Akash Vacher 2022-09-30 22:59:56 -07:00
parent 7caefb975c
commit 21cfe5e127
1 changed files with 31 additions and 30 deletions

View File

@ -13,14 +13,9 @@ chrome.runtime.onInstalled.addListener(function() {
}); });
}); });
chrome.contextMenus.onClicked.addListener(function(item, tab) { function sendVideoUrlToMetubeAndSwitchTab(videoUrl, metubeUrl, tab) {
chrome.storage.sync.get(['metube'], function(data) { console.log("Sending videoUrl=" + videoUrl + " to metubeUrl=" + metubeUrl);
if (data === undefined || !data.hasOwnProperty('metube') || data.metube === "") { fetch(metubeUrl + "/add", {
openTab(chrome.runtime.getURL('options.html'), tab);
return
}
fetch(data.metube + "/add", {
method: 'POST', method: 'POST',
headers: { headers: {
'Accept': 'application/json', 'Accept': 'application/json',
@ -28,27 +23,33 @@ chrome.contextMenus.onClicked.addListener(function(item, tab) {
}, },
body: JSON.stringify({ body: JSON.stringify({
"quality": "best", "quality": "best",
"url": item.linkUrl "url": videoUrl
}) })
}) }).then(function(res) {
.then(function(res) {
if (res.ok === true && res.status === 200) { if (res.ok === true && res.status === 200) {
return res.json(); return res.json();
} }
// todo fix it // todo fix it
alert("error :: code " + res.status); alert("error :: code " + res.status);
}) }).then(function(result) {
.then(function(result) {
if (result.status === "ok") { if (result.status === "ok") {
openTab(data.metube, tab); openTab(metubeUrl, tab);
} else { } else {
// todo fix it // todo fix it
alert("error :: " + json); alert("error :: " + json);
} }
}) }).catch(function(res) {
.catch(function(res) {
alert("error :: " + res); alert("error :: " + res);
}) });
}
chrome.contextMenus.onClicked.addListener(function(item, tab) {
chrome.storage.sync.get(['metube'], function(data) {
if (data === undefined || !data.hasOwnProperty('metube') || data.metube === "") {
openTab(chrome.runtime.getURL('options.html'), tab);
return
}
sendVideoUrlToMetubeAndSwitchTab(item.linkUrl, data.metube, tab);
}); });
}); });