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

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

$('body').prepend('

test

');

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

 $('body').prepend('
'); $('#topbar').load('topbar.html');

topbar.html是:

 

test

但是,当我将其更改为此时,网页会被破坏。 大部分内容都消失了,我最终看到了一些广告。 我甚至看不到’测试’标题。 我已经检查过以确保页面上没有其他“topbar”ID。 怎么了?

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

 chrome-extension:///topbar.html 

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

 chrome.extension.getURL("topbar.html") 

现在,如果您尝试:

 $('#topbar').load(chrome.extension.getURL("topbar.html")); 

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

content_script.js

 chrome.extension.sendRequest({cmd: "read_file"}, function(html){ $("#topbar").html(html); }); 

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 }); } }) 

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

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

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