我正在編寫我的第一個Chrome擴展程序,它使用上下文菜單(右鍵單擊和選項出現)。當突出顯示文本並從右鍵單擊菜單中選擇ExtensionName選項時,它會打開一個新選項卡,並將其作爲查詢傳遞給我的組織擁有的目錄。問題是它只能使用一次。當文本突出顯示並右鍵單擊時,上下文菜單中的選項仍然顯示,但選擇ExtensionName選項無法生成具有目錄結果的另一個選項卡。Chrome擴展上下文菜單僅適用於一次
我想讓用戶能夠在瀏覽器會話中多次使用它,就像大多數其他Chrome擴展一樣。在Chrome擴展菜單中重新加載擴展程序可修復此問題。我認爲它與我的後臺腳本rightclick.js
中發生的事件處理有關。我不太熟悉JavaScript中或Chrome環境中的事件處理,所以我們將不勝感激。
的manifest.json
{
"name": "ExtensionName",
"description": "Right-click text to search the given directory.",
"manifest_version": 2,
"version": "1.0",
"permissions": ["contextMenus"],
"icons": {
"16": "icon-bitty.png",
"48": "icon-small.png",
"128": "icon-large.png"
},
"background": {
"scripts": ["rightclick.js"]
}
}
rightclick.js
var selection_callbacks = [];
chrome.extension.onMessage.addListener(function (request) {
var callback = selection_callbacks.shift();
callback(request);
});
function getSelection(callback) {
selection_callbacks.push(callback);
chrome.tabs.executeScript(null, { file:"selection.js" });
};
function createDirectoryRequest(selectText) {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "THE URL FOR THE DIRECTORY GOES HERE");
form.setAttribute("target", "_blank");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("id", "search_generic_search_terms);");
hiddenField.setAttribute("name", "search[generic_search_terms]");
hiddenField.setAttribute("value", selectText);
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
}
chrome.contextMenus.create({title: 'ExtensionName "%s"',
contexts:["selection"],
onclick: function(info, tab){ createDirectoryRequest(info.selectionText); }})
selection.js
chrome.extension.sendResponse(window.getSelection().toString());
我知道這可能不是一個困難的問題,我只是難以置信新的這個,所以任何幫助將不勝感激。謝謝。
我使用第二個選項。我打過的唯一一個打嗝是window.open(「目錄的URL到這裏」,「window」+ i);'',我不得不將URL部分留空以使其正常工作。我不知道這是否是一個普遍問題,或者是因爲我的目錄而發生的事情,但無論如何,感謝您的幫助! – tacocat