javascript - 将 html 加载到页面元素中(chrome 扩展)

标签 javascript jquery dom google-chrome-extension

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

$('body').prepend('<div id="topbar"><h1>test</h1></div>');

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

$('body').prepend('<div id="topbar"></div>');
$('#topbar').load('topbar.html');

topbar.html 所在位置:

<h1>test</h1>

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

最佳答案

扩展文件夹内文件的 URL 具有以下格式:

chrome-extension://<ID>/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);
});

背景.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,然后重复使用它。

关于javascript - 将 html 加载到页面元素中(chrome 扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5643263/

相关文章:

php - 比较两个 texbox 中 mysql 数据库的值,无需提交表单

javascript - 如何在类构造函数中使用原型(prototype)方法

javascript - Angularjs 检测新 Dom 上的指令

javascript - 我可以将带有 GIF 内容的 $.post 函数的结果放入 javascript Image 对象吗?

javascript - jQuery:需要 "refresh"一个小部件

javascript - 使用 Javascript 附加选取框 div

javascript - 何时使用 `#` 符号来获取 DOM 元素?

javascript - 将值提交到另一个页面 iframe 表单

javascript - 如何 .hide() 来自类的单个 div

c# - 如何使用 ActiveXObject 从 JavaScript 创建我的 C# Com 类