Marek Sebera
Marek Sebera

Reputation: 40681

XMLHttpRequest for chrome-extension protocol

I'm using background page and I need to inject some code into current tab contents.

so I do following:

And from page content I need to load html resource from within extensions folder.

but using this XMLHttpRequest gives me error Cross origin requests are only supported for HTTP

handled by XMLHttpRequest by error NETWORK_ERR: XMLHttpRequest Exception 101

So how am I supposed to solve it?

Note: address is like chrome-extension://someextensionid/file.html

Upvotes: 1

Views: 1618

Answers (2)

serg
serg

Reputation: 111345

Instead of:

btoa(loadXHR(chrome.extension.getURL('file.html')))

you should be able to just use:

loadXHR('file.html')

as XMLHttpRequest understands relative path (with root being your extension folder).

Upvotes: 1

Marek Sebera
Marek Sebera

Reputation: 40681

Solved using:

btoa(loadXHR(chrome.extension.getURL('file.html')))

where

  • btoa = string to base64
  • loadXHR = synchronous xmlhttprequest
  • chrome.extension.getURL = resolve address in extension folder

this was done in background_page and passed to script in foreground using

chrome.tabs.executeScript

and in foreground, script converted string to html-string and dom object

var div = document.createElement('div');
div.innerHTML = atob(tbr);
document.body.appendChild(div);

where

  • document.createElement = creates new "" element
  • innerHTML = HTML value of div element, so setting it will create DOM parseable content
  • atob = base64 string to decoded version
  • document.appendChild = appends div with HTML content to body element

Upvotes: 2

Related Questions