form-copypasta-crx/background.js

69 lines
1.8 KiB
JavaScript

chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({ "id": "copy-form", "title": "Copy Form", "contexts": ["editable"] });
chrome.contextMenus.create({ "id": "paste-form", "title": "Paste Form", "contexts": ["editable"], enabled: false });
chrome.contextMenus.create({ "id": "paste-form2", "title": "Paste Form (with Hidden)", "contexts": ["editable"], enabled: false });
});
chrome.contextMenus.onClicked.addListener(function(msg, tab) {
switch (msg.menuItemId) {
case "copy-form":
copyFormContextMenu(tab);
break;
case "paste-form":
pasteFormContextMenu(tab, false);
break;
case "paste-form2":
pasteFormContextMenu(tab, true);
break;
default: break;
}
});
chrome.commands.onCommand.addListener(function (command) {
switch (command) {
case 'copy-form':
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
copyFormContextMenu(tabs[0]);
});
break;
case 'paste-form':
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
pasteFormContextMenu(tabs[0], false);
});
break;
default: break;
}
});
function copyFormContextMenu(tab) {
chrome.tabs.sendMessage(tab.id, { action: "copy" }, function(response) {
try {
chrome.storage.local.set({ 'clipboard': JSON.stringify(response) },function() {
chrome.contextMenus.update("paste-form", { enabled: true });
chrome.contextMenus.update("paste-form2", { enabled: true });
});
} catch (err) {
// Do nothing
}
});
}
function pasteFormContextMenu(tab, includeHiddenEl) {
chrome.storage.local.get('clipboard', function(response) {
try {
const payload = {
action: (includeHiddenEl === true ? "paste2" : "paste"),
formData: JSON.parse(response.clipboard)
};
chrome.tabs.sendMessage(tab.id, payload);
} catch (err) {
// Do nothing
}
});
}