Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - Loading html into page element (chrome extension)

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

where topbar.html is:

<h1>test</h1>

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

Now if you try to do:

$('#topbar').load(chrome.extension.getURL("topbar.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
        });
    }
})

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...