将html加载到页面元素(chrome扩展名)

Col*_*lin 22 javascript jquery dom google-chrome-extension

我正在尝试编写Chrome扩展程序,在某些网页的顶部会有一个栏.如果我有这样的内容脚本:

$('body').prepend('<div id="topbar"><h1>test</h1></div>');
Run Code Online (Sandbox Code Playgroud)

一切看起来都不错,但我最终想要的是这样的:

$('body').prepend('<div id="topbar"></div>');
$('#topbar').load('topbar.html');
Run Code Online (Sandbox Code Playgroud)

topbar.html是:

<h1>test</h1>
Run Code Online (Sandbox Code Playgroud)

但是当我改变它时,网页被破坏了.大多数内容都消失了,我最终看到了一些广告.我甚至看不到'测试'标题.我已经检查过以确保页面上没有其他"topbar"ID.怎么了?

ser*_*erg 35

extenion文件夹中的文件的URL具有以下格式:

chrome-extension://<ID>/topbar.html
Run Code Online (Sandbox Code Playgroud)

您可以通过运行来获取此路径:

chrome.extension.getURL("topbar.html")
Run Code Online (Sandbox Code Playgroud)

现在,如果您尝试:

$('#topbar').load(chrome.extension.getURL("topbar.html"));
Run Code Online (Sandbox Code Playgroud)

由于跨省政策,它不会让你.后台页面没有此限制,因此您需要在那里加载HTML并将结果传递给内容脚本:

content_script.js:

chrome.extension.sendRequest({cmd: "read_file"}, function(html){
    $("#topbar").html(html);
});
Run Code Online (Sandbox Code Playgroud)

background.html:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.cmd == "read_file") {
        $.ajax({
            url: chrome.extension.getURL("topbar.html"),
            dataType: "html",
            success: sendResponse
        });
    }
})
Run Code Online (Sandbox Code Playgroud)

在现实世界中,您可能只会阅读topbar.html一次,然后重复使用它.

  • 应在清单中指定`web_accessible_resources`.请参阅:http://developer.chrome.com/extensions/manifest.html#web_accessible_resources (7认同)
  • $ .get(chrome.extension.getURL("topbar.html"),函数(topbarContent){...},'html'); bit对我来说很好 - 我没有在控制台中看到任何跨源错误. (5认同)

小智 5

虽然上述解决方案确实有效,但需要注意的一件事是您需要从事件处理程序返回 true,以便在 $.ajax 调用成功后通信端口仍然可用。

请参阅下面的详细信息。 https://code.google.com/p/chromium/issues/detail?id=307034

  • 如果您想扩展其他人的答案,最好对他们的答案发表评论,而不是发表第二个评论。 (10认同)

fgu*_*len 5

纯js解决方案。

在你的manifest.json

{
  "manifest_version": 3,
  # [...]
  "web_accessible_resources": [{
      "matches": ["<all_urls>"],
      "resources": ["topbar.html"]
  }]
}
Run Code Online (Sandbox Code Playgroud)

在你的content.js

async function load_toolbar() {
  let newElement = new DOMParser().parseFromString('<div id="toolbar"></div>', 'text/html').body.childNodes[0];
  let toolbar_url = chrome.runtime.getURL("toolbar.html");

  document.querySelector("body").appendChild(newElement);
  document.getElementById("toolbar").innerHTML = await (await fetch(toolbar_url)).text();
}

load_toolbar();
Run Code Online (Sandbox Code Playgroud)