Loading html into page element (chrome extension)

后端 未结 3 935
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 00:51

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(\'&l         


        
3条回答
  •  没有蜡笔的小新
    2020-12-13 01:21

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

    chrome-extension:///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.

提交回复
热议问题