简体   繁体   中英

Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a part of the Chrome extension?

I am working on a Chrome extension content script that will, on specific pages, inject additional content onto the page to add functionality to an existing site.

I have an HTML file that is in my Chrome extension that contains the template for content that will be added. I am hoping I can use jQuery to retrieve that HTML template. I initially tried a simple jQuery AJAX request, like this:

var url = "template.html";

$.get(url,function(data, textStatus, jqXHR){
    console.log("Got the template!");
    console.log(data);
},"html");

However, this results in the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://gmjipglelhnlbakmlobgffnpceaalnnc' is therefore not allowed access.

This sounds like a Chrome Extensions permissions issue , and the relevant permission seems to be the [scheme]:[host]/* permissions issue. My extension ID is gmjipglelhnlbakmlobgffnpceaalnnc , so I tried adding permission for chrome-extension://gmjipglelhnlbakmlobgffnpceaalnnc/ (which according to this is the prefix for fully qualified Chrome Extension packaged resources).

That didn't work, as Chrome told me Permission 'chrome-extension://gmjipglelhnlbakmlobgffnpceaalnnc/' is unknown or URL pattern is malformed .

A little more reading and I found that there is a specific facility, described here under extension origin , to request packaged resources. That's all well and good, but I would prefer to use a uniform API to request resources, ie, to be able to use jQuery to pull down my template files, as I've been doing for regular "vanilla" web apps (ie, not Chrome extensions).

Is there a way to configure my Chrome extension permissions so that I can request "extension origin" resources via jQuery's AJAX facilities?

Found my answer. You have to explicitly add either the individual extension resources, or patterns that match your extension resources, in the manifest via web_accessible_resources .

Once you've done this, you can construct the URL using chrome.extension.getURL(resourcePath) .

Here's an excerpt from my manifest:

"web_accessible_resources" : [
    "*.html"
]

And here's the code I'm using to request my template file:

var url = chrome.extension.getURL("template.html");
$.get(url,function(data, textStatus, jqXHR){
    console.log("Got the template!");
    console.log(data);
},"html");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM