我正在制作一个简单的第一个扩展名,因为之前我没有使用过javascript,而且我在这方面有点卡住了。
基本上我已经减少了源html来获取图片网址,我想保存它。我正在使用来自here的getPagesSource.js
(虽然我使用上下文菜单而不是弹出窗口)来获取源代码,但我发现我无法在获取后获取图像网址。
如果我将带有测试URL的下载功能放在context_click()
中,它可以正常工作并弹出下载框,但如果它在该侦听器功能中(具有相同的URL),则它不会执行任何操作。
如何获取使用下载功能的URL?
的manifest.json:
{
"name": "Test",
"version": "1.0",
"manifest_version": 2,
"description": "test",
"browser_action": {
"default_icon": "icon.png"
},
"permissions": ["tabs", "contextMenus", "<all_urls>", "downloads"],
"background": {"page": "background.html"},
}
main.js(在background.html中链接):
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
//message.innerText = request.source;
var page_source = request.source;
var image_url = page_source.(do things);
//This works
//chrome.tabs.create({url: image_url});
//This doesn't, and it's what I want to get working
//chrome.downloads.download({
// url: image_url,
// saveAs: true
//});
//Workaround that doesn't have a save dialogue
var a = document.createElement('a');
a.href = image_url;
var url_parts = image_url.split('/');
a.download = url_parts[url_parts.length - 1];
a.click();
}
});
function context_click() {
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
});
//This works from this point
//chrome.downloads.download({
// url: 'some random url',
// saveAs: true
//});
}
chrome.contextMenus.create({
title: "test",
//contexts:["selection"], // ContextType
onclick: context_click
});