我正在尝试将文件下载到我的下载文件中。我正在动态地在网页上创建一个按钮,并且在按下该按钮时就像下载一样。因为什么原因,当我点击按钮没有任何反应,我不知道为什么。请帮忙
background.js代码
function SendRequest(url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.open("GET", url, true);
xhr.send();
}
var objurl = localStorage.getItem("OBJURL");
function EditContent(objurl){
chrome.downloads.download({url:objurl,filename:"Object Edit - Chrome Extension.rbxl",conflictAction:"overwrite"})
}
item.js
contentInput.onclick = function(){
var assetid = $('.thumbnail-span').attr("data-3d-url")
var baseurl = 'http://www.roblox.com'
SendRequest(baseurl + assetid, function (response) {
var response = response; //Easy Peasy
var jsonObject = JSON.parse(response); //Parse the response
localStorage.setItem("URL1", jsonObject.Url); //It's saved!
var test = localStorage.getItem("URL1"); //Let's grab it and save it to a variable
console.log(test); //Logs "Hello World!"
});
var url1 = localStorage.getItem("URL1");
SendRequest(url1, function (response1) {
var response = response1; //Easy Peasy
var jsonObject = JSON.parse(response); //Parse the response
localStorage.setItem("OBJ", jsonObject.obj); //It's saved!
});
var hashdecode = "http://roblox.com/thumbnail/resolve-hash/"
var objhash = localStorage.getItem("OBJ");
SendRequest(hashdecode + objhash, function (objresponse) {
var response = objresponse; //Easy Peasy
var jsonObject = JSON.parse(response); //Parse the response
localStorage.setItem("OBJURL", jsonObject.Url); //It's saved!
});
chrome.extension.sendRequest({
action: "EditContent",
})
}
答案 0 :(得分:0)
哦,小伙子。这里有很多错误。我的意思是 很多 。
chrome.extension.sendRequest
已弃用。请改用chrome.runtime.sendMessage
。
那就是说,你正在发送消息,但实际上没有人听到它。 action: "something"
并不代表任何先验,你需要自己做出反应:
// background.js
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse){
if(message.action == "EditContent") {
/* do stuff */
}
}
);
localStorage
。事实上,后台脚本有自己的localStorage
(绑定到chrome-extension://whateverisyourid/
域)副本,内容脚本与页面共享。
您应该使用共享但工作方式不同的chrome.storage
,或者在邮件中传递您需要的内容,例如:
{action: "EditContent", objurl: jsonObject.Url}
并使用它:
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse){
if(message.action == "EditContent") {
EditContent(message.objurl)
}
}
);
在后台脚本中定义的函数(SendRequest
)无法在内容脚本中调用。您需要将其移动到内容脚本,或从后台脚本中调用它。
您的SendRequest
是异步的。如果你写的东西如下:
function f(){
action1();
SendRequest(url1, function(response){
action2();
});
action3();
SendRequest(url2, function(response){
action4();
});
action5();
}
f();
然后就会发生这种情况:
action1()
SendRequest
会将请求排入url1
,但不会等待action3()
SendRequest
会将请求排入url2
,但不会等待action5()
f()
终止,队列中的下一个是第一个请求。action2()
即可运行。action4()
即可运行。我想这甚至会被交换,具体取决于首先完成哪个请求。
你看到了问题吗?您需要链接异步调用:
function f(){
action1();
SendRequest(url1, function(response){
action2();
action3();
SendRequest(url2, function(response){
action4();
action5();
});
});
}
这可能不是完整的问题列表,当然也不是完整的工作代码。
请请下次调试您的扩展程序。您可以从页面控制台中的内容脚本( Ctrl + Shift + J )和{{1}的后台页面控制台访问错误在开发者模式下。