从内容脚本将 HTML 注入页面 [英] Inject HTML into a page from a content script
问题描述
我正在构建一个 Chrome 扩展程序,我需要在几个网站上覆盖一团 html.目前我正在使用 JQuery .Get
从我的服务器中提取 html.为了提高性能,我想知道是否可以将 html 作为文件包含在扩展目录中并直接从那里访问源代码?有谁知道这是否可能?
I am building a Chrome Extension and I have a requirement to overlay a blob of html on top of a few websites. At the moment I am using a JQuery .Get
to pull the html from my server. In order to improve performance I am wondering if it is possible to include the html as a file in the extension directory and access the source directly from there? Does anyone know if this is possible?
更新
Rob 的建议可以解决问题(请参阅已接受的答案).唯一的额外步骤是在 web_accessible_resources 下的清单中注册文件.
Rob's suggestion does the job (see accepted answer). The only additional step is to register the file in the manifest under web_accessible_resources.
{
...
"web_accessible_resources": [
"myimportfile1.html",
"myimportfile2.html"
],
...
}
推荐答案
是的,这是可能的.使用 chrome.runtime.getURL
获取绝对值资源的 URL.例如:
Yes, that's possible. Use chrome.runtime.getURL
to get an absolute URL for the resource. For example:
第 1 步(标准 JavaScript):
Step 1 (standard JavaScript):
fetch(chrome.runtime.getURL('/template.html')).then(r => r.text()).then(html => {
document.body.insertAdjacentHTML('beforeend', html);
// not using innerHTML as it would break js event listeners of the page
});
第 1 步(jQuery):
Step 1 (jQuery):
$.get(chrome.runtime.getURL('/template.html'), function(data) {
$(data).appendTo('body');
// Or if you're using jQuery 1.8+:
// $($.parseHTML(data)).appendTo('body');
});
第 2 步:
在 manifest.json 中注册资源>web_accessible_resources:
Register the resource in the manifest.json under web_accessible_resources:
"web_accessible_resources": [
"template.html",
"foo.jpg"
]
这篇关于从内容脚本将 HTML 注入页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!