javascript - jQuery 外部文本请求图像

标签 javascript jquery google-chrome-extension

我正在开发一个 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/

相关文章:

javascript - 如何将 promise 的结果保存到变量中?

javascript - 如何获取 span 的 id 并使其不显示动态生成的内容?

javascript - 内联 Javascript 单击功能,用于在 chrome 扩展中动态添加具有动态 id 的元素

javascript - 移动 Web 应用程序 - 多页面还是 AJAX?

javascript - Angular 模型更新后获取 DOM 元素

javascript - 限制bootstrap 3分页显示的页数

jquery - 循环遍历表单提交中的每个 'required'字段

javascript - chrome...addListener,如何等待 chrome.storage.sync.get?

javascript - 发出 executeScript 权限

javascript - jQuery zclip 仅在第一次单击时不起作用