views:

231

answers:

1

Hi,everyone! I am a beginner with chrome extension. In my content_script.js, how can a get an array in Javascript from background.html?

+1  A: 

I did it like this: (assuming you have an array foo in background.html)

chrome.extension.getBackgroundPage().foo

But apparently, that only works for things like popup.html, etc. To get data from your background page in a content_script.js file, you need to use:

chrome.extension.connect()

The API docs are here.

perimosocordiae
I tried this method,but it seems do not work.In my background.html,there is an array LEN,and in my content_script.js,i write like this:alert( chrome.extension.getBackgroundPage().LEN.length );but it don't work. :(
T_t
Hm. Try inspecting content_script.js with the dev tools, and see what happens when you type chrome.extension.getBackgroundPage() at the console.
perimosocordiae
There is the error info,"Resource interpreted as document but transferred with MIME type application/x-javascript.",and i can't figure it out...:(
T_t
Oh! I had that same error. You need to put your javascript in an HTML page, not a .js file. Try renaming it to content_script.html and adding <script> tags, and it should work!
perimosocordiae
Hm,i am a little confused.In the offical guide pages,it said that the type of a content_script file must be .js.If i add <script>,how could it work?I tried, but failed. :(
T_t
Ah, you're right. Sorry, disregard my last message... You need to use chrome.extension.connect() http://code.google.com/chrome/extensions/extension.html#method-connect
perimosocordiae