8

I am developing a chrome extension that uses jQuery/Zepto in the content script. Now, the extension is meant to run on every website, which means a copy of jQuery/Zepto is loaded on each tab the user opens.

Is there a way to share the jQuery/Zepto object between the various content scripts?

I know content scripts can communicate with the background script. I was hoping to be able to let the background script have access to the jQuery object and return a reference to it, to each of the content scripts. But I realized only JSON messages can be passed between content and background scripts.

Is there any way to achieve what I want?

Himanshu P
  • 9,586
  • 6
  • 37
  • 46
  • No, you cannot share direct function references between content scripts. (duplicate question: [How to transfer data between the content scripts of two different tabs?](http://stackoverflow.com/questions/11597416/how-to-transfer-data-between-the-content-scripts-of-two-different-tabs)). – Rob W Dec 03 '12 at 15:35
  • Post this as an answer and I'll accept it. Btw, a question - I thought yesterday that getting jQuery included in every page might not actually be a problem, because unlike the actual resources of a webpage this doesn't have to be downloaded. Given that the average size of a webpage is approaching 1MB (as I read online), the increase in the memory consumption should not be much of a problem I reasoned. Does that seem to make sense? – Himanshu P Dec 04 '12 at 06:04

2 Answers2

9

Content scripts in different tabs do not have access to each other's JavaScript objects either.

Chrome supports communication between content scripts and/or the background page via chrome.runtime.sendMessage + .onMessage. Because all messages are JSON-serialized, JavaScript object cannot be "leaked" to other contexts in this way.

So: No, you cannot share objects such as jQuery with (content scripts in) other tabs.

Anonymous
  • 11,748
  • 6
  • 35
  • 57
Rob W
  • 341,306
  • 83
  • 791
  • 678
1

Execution environment of Content Scripts ensure content scripts can communicate among themselves

Ex:

"content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["myscript.js","myscript1.js"]
    }
  ]
}

A Individual DOM Environment where content scripts ["myscript.js","myscript1.js"] injected ensures myscript1.js have access to all contents (Functions,Variables) of myscript.js, but this stops from two Individual DOM Environment's being communicating.

Having said that, What Limitation\requirement you see in Content Scripts which calls for requirement where message passing needs background pages to access DOM of injected pages?

Please Elaborate

Sudarshan
  • 18,140
  • 7
  • 53
  • 61