Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

google chrome - Inject HTML into a page from a content script

I am building a Chrome Extension and I have a requirement to overlay a blob of html on top of a few websites. At the moment I am using a JQuery .Get to pull the html from my server. In order to improve performance I am wondering if it is possible to include the html as a file in the extension directory and access the source directly from there? Does anyone know if this is possible?

UPDATE

Rob's suggestion does the job (see accepted answer). The only additional step is to register the file in the manifest under web_accessible_resources.

{
   ...
   "web_accessible_resources": [
       "myimportfile1.html",
       "myimportfile2.html"
    ],
    ...
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Yes, that's possible. Use chrome.runtime.getURL to get an absolute URL for the resource. For example:

Step 1 (standard JavaScript):

fetch(chrome.runtime.getURL('/template.html')).then(r => r.text()).then(html => {
  document.body.insertAdjacentHTML('beforeend', html);
  // not using innerHTML as it would break js event listeners of the page
});

Step 1 (jQuery):

$.get(chrome.runtime.getURL('/template.html'), function(data) {
    $(data).appendTo('body');
    // Or if you're using jQuery 1.8+:
    // $($.parseHTML(data)).appendTo('body');
});

Step 2:

Register the resource in the manifest.json under web_accessible_resources:

  "web_accessible_resources": [
    "template.html",
    "foo.jpg"
  ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...