Skip to content

Commit

Permalink
change menu title dynamically when tab changes
Browse files Browse the repository at this point in the history
  • Loading branch information
nettee committed Oct 11, 2019
1 parent 863cc5f commit e96f640
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
41 changes: 34 additions & 7 deletions background.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ function notifyCopied(content) {
});
}

function compress(s, len) {
if (s.length <= len) {
return s;
} else {
return s.substring(0, len-3) + '...';
}
}

var pageTitle = 'title';
var pageUrl = 'url';
var pageSelectionText = 'selected text';

var menuItems = {};

menuItems.root = chrome.contextMenus.create({
Expand All @@ -40,9 +52,9 @@ menuItems.root = chrome.contextMenus.create({
contexts: ['all'],
});

menuItems.selectedTextToMarkdown = chrome.contextMenus.create({
menuItems.selectionToMarkdown = chrome.contextMenus.create({
parentId: 'root',
title: 'Selected text',
title: 'Selection as markdown',
type: 'normal',
contexts: ['selection'],
onclick: function (info, tab) {
Expand Down Expand Up @@ -93,6 +105,24 @@ menuItems.pageLinkSelectedText = chrome.contextMenus.create({
}
});

function updateMenuTitle() {
chrome.contextMenus.update(menuItems.pageLinkTitle, {
title: `Current page: [${pageTitle}](${pageUrl})`,
});
chrome.contextMenus.update(menuItems.pageLinkSelectedText, {
title: `Current page: [${pageSelectionText}](${pageUrl})`,
});
}

chrome.tabs.onActivated.addListener(function(activeInfo) {
const tabId = activeInfo.tabId;
chrome.tabs.get(tabId, function (tab) {
pageTitle = compress(tab.title, 15);
pageUrl = compress(tab.url, 30);
updateMenuTitle();
})
});

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.request === 'selectedHtml') {
const html = message.selectedHtml;
Expand All @@ -103,10 +133,7 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
notifyCopied(markdown);

} else if (message.request === 'selectedText') {
const text = message.selectedText;
console.log('text: ', text);
chrome.contextMenus.update(menuItems.pageLinkSelectedText, {
title: `Current page: [${text}](url)`,
});
pageSelectionText = message.selectedText;
updateMenuTitle();
}
});
1 change: 1 addition & 0 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"version": "0.1.0",
"permissions": [
"contextMenus",
"background",
"tabs",
"storage",
"notifications",
Expand Down

0 comments on commit e96f640

Please sign in to comment.