将html加载到页面元素(chrome扩展名) [英] Loading html into page element (chrome extension)

查看:121
本文介绍了将html加载到页面元素(chrome扩展名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a Chrome extension that will have a bar at the top of certain webpages. If I have my content script like this:

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

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

everything looks good, but what I ultimately want is something like this:

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

topbar.html是:

where topbar.html is:

<h1>test</h1>

当我将其更改为此时,网页被破坏。大部分的内容都消失了,我只是看到一些广告。我甚至看不到'测试'标题。我已经检查,确保页面上没有其他顶栏ID。什么问题?

When I change it to this, though, the webpage is clobbered. Most of the content disappears, and I just end up seeing some of the ads. I can't even see the 'test' header. I've checked to make sure there's no other 'topbar' id on the page. What's wrong?

推荐答案

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

URL of a file inside an extenion folder has the following format:

chrome-extension://<ID>/topbar.html

您可以通过运行以下方式获取此路径:

You can get this path by running:

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

现在,如果您尝试:

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

它不会让你因为跨原产地的政策。背景页面没有这个限制,所以你需要加载HTML并将结果传递给内容脚本:

it wouldn't let you because of cross-origin policy. Background pages don't have this limitation, so you would need to load HTML there and pass result to a content script:

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只有一次,然后重新使用它。

In a real world you probably would read topbar.html only once and then reuse it.

这篇关于将html加载到页面元素(chrome扩展名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆