我正在开发用于 Zendesk 的 chrome 扩展程序,该扩展程序的功能之一是为给定的票证收集两种不同格式的字符串,并以摘要或“时间轴”格式将它们打印出来。我有这个功能,但有一些我无法弄清楚的错误。
我希望在 chrome 扩展中选择自定义上下文菜单选项时,该功能只运行一次。 目前它会运行几次,等于用户在选择上下文菜单选项之前按下的右键单击次数。 消息从内容脚本(在页面上下文中运行)发送到后台脚本。该消息为上下文菜单选项初始化 onClicked 侦听器,然后将更新发送回内容脚本以运行该功能。
我试图以相反的方式执行此操作以查看它是否会解决问题,但由于内容脚本在页面上下文中运行以访问页面 ckeditor 实例,我无法弄清楚如何这样做。在我看来,每次用户按下右键单击时,消息都会排队,然后一旦按下上下文菜单项,队列就会清空。
script.js(内容脚本)
function generateTimeline(editingArea)
{
chrome.runtime.sendMessage("nmkeddobbgmklaojjmkimpaffccencgn", {operation : "UPD" }, function(response) {
if(response === "UPDATED")
{
const editorInstance = editingArea.ckeditorInstance;
const eventContainer = getEventContainer(editingArea);
let dateTimeRecords = getInternalCommentTextNodes(eventContainer);
dateTimeRecords.sort(dateComparator);
duplicateChecker(dateTimeRecords);
editorInstance.model.change(writer => {
for(record of dateTimeRecords)
{
const paragraph = writer.createElement('paragraph');
writer.append(paragraph, editorInstance.model.document.getRoot());
const textNode = writer.createText(record.tag + ' ' + record.comment);
writer.append(textNode, paragraph);
}
});
}
});
}
document.addEventListener('mouseup', function(e) {
if(this.activeElement.getAttribute("role") === "textbox" && this.activeElement.getAttribute("aria-label") === "Rich Text Editor. Editing area: main")
{
const editingArea = singletonEventListener(this.activeElement);
// left click
if(e.button === 0)
{
createKeyPressListener(editingArea);
}
//right click
if(e.button === 2)
{
generateTimeline(editingArea);
}
}
});
背景.js
const timeLineGenerator = {
"id": "timeLineGenerator",
"title": "Generate Timeline",
"contexts":["editable"]
};
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create(timeLineGenerator);
});
function manageMenuListener(request, sender, sendResponse)
{
if(request.operation === "UPD")
{
if(chrome.contextMenus.onClicked.hasListener)
{
chrome.contextMenus.onClicked.removeListener();
console.log("listener removed");
}
chrome.contextMenus.onClicked.addListener(() => {
return sendResponse("UPDATED");
});
}
}
chrome.runtime.onMessageExternal.addListener(manageMenuListener);
清单.json
{
"manifest_version": 3,
"name": "Zendesk Date Time Tool",
"description": "Inserts a date time string when a user defined key is pressed",
"permissions":[
"scripting",
"contextMenus",
"activeTab",
"tabs"
],
"host_permissions":["<all_urls>"],
"version": "1.0",
"icons":{
"16":"/icons/icon16.png",
"48":"/icons/icon48.png",
"128":"/icons/icon128.png"
},
"action": {
"default_popup": "/src/index.html",
"default_icon": "/icons/icon128.png"
},
"background":{
"service_worker":"/src/background.js"
},
"content_scripts":[{
"world": "MAIN",
"matches":["https://.zendesk.com/*"],
"js":["/src/script.js"],
"run_at":"document_end"
}],
"externally_connectable": {
"matches": ["https://.zendesk.com/*"]
}
}