我正在开发一个 Chrome 扩展,它使用 jquery 来解析页面的源代码以获取特定的内容。在示例中,我正在浏览维基百科来获取类别。
我通过以下方式获取页面来源
chrome.tabs.executeScript(tabId, {
code: "chrome.extension.sendMessage({action: 'getContentText', source: document.body.innerHTML, location: window.location});"
}, function() {
if (chrome.extension.lastError)
console.log(chrome.extension.lastError.message);
});
然后我正在监听此消息(成功),然后使用 jquery 解析对象的 source
键,如下所示
if (request.action == "getContentText")
{
//console.log(request.source);
$('#mw-normal-catlinks > ul > li > a', request.source).each(function()
{
console.log("category", $(this).html());
});
}
这按预期工作并记录所有类别链接innerHTML 的列表。然而,问题发生在 jQuery 选择器上,它尝试加载 request.source
中包含的图像。这会导致错误,例如
获取 chrome-extension://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Padlock-silver.svg/20px-Padlock-silver.svg.png net::ERR_FAILED
这些是有效的链接,但是它们是从我的扩展程序中使用 chrome-extension://
前缀(无效)调用的(不需要)。我不确定为什么 jquery 会尝试使用选择器从源内部评估/请求图像
最佳答案
我猜这是因为维基百科在其图像上使用相对路径(而不是 https://或 http://,只是//- 因此加载的内容是相对于服务器的)。请求是由 jQuery 发出的,您可以看到 here how to fix this issue (将来,请确保更彻底地搜索)。
关于javascript - jQuery 外部文本请求图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29321780/