【发布时间】:2017-04-04 00:54:10
【问题描述】:
免责声明:我是 JavaScript 新手,之前从未开发过 Chrome 扩展程序。
我正在尝试开发一个 Chrome 扩展程序,当用户在页面上选择一些文本,右键单击,然后单击上下文菜单按钮时运行一些 JavaScript。我已经确定(基于从 Chrome 控制台运行它)我编写的 JavaScript 按预期运行。现在剩下的就是做一个扩展。
我可以让扩展程序加载,我可以让它出现在页面上并显示为运行。但是,它似乎什么也没做,控制台也没有返回任何输出。 (我读到我不能使用事件页面运行内联 JavaScript,因此使用 addListener。)我是否错误地设置了上下文菜单?我的脚本中是否有一个(或多个)错误?
manifest.json
{
"name": "My Extension",
"description": "sample",
"version": "0.0.1",
"permissions": ["contextMenus"],
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"manifest_version": 2
}
background.js
chrome.runtime.onInstalled.addListener(function() {
var context = "selection";
var title = "My Extension";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
"id": "context" + context});
});
chrome.contextMenus.onClicked.addListener(getSHA);
// Get file path of file to be staged
// Get SHA
function getSHA(){
stagedFile = window.getSelection().toString()
console.log(stagedFile)
baseURL = window.location.href.slice(0, -6);
prNumber = baseURL.slice(-4);
xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.github.com/repos/kubernetes/kubernetes.github.io/pulls/"+prNumber, false);
xhr.send();
json_data = JSON.parse(xhr.responseText);
shaValue = (json_data.head.sha)
console.log("SHA: "+shaValue)
getNetlify;
};
// Get Netlify URL
function getNetlify(){
xhr2 = new XMLHttpRequest();
xhr2.open("GET", "https://api.github.com/repos/kubernetes/kubernetes.github.io/commits/"+shaValue+"/status", false);
xhr2.send();
json_data2 = JSON.parse(xhr2.responseText, function(key, value) { if (key == "target_url" && value.includes("netlify")) { netlifyURL = value; }});
openStaging
};
// Stage file
function openStaging(){
window.open(netlifyURL+"/"+stagedFile)
};
【问题讨论】: