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?
Communication between extensions and their content scripts works by using message passing. Either side can listen for messages sent from the other end, and respond on the same channel. A message can contain any valid JSON object (null, boolean, number, string, array, or object).
Background Script - Provides persistence and handles background events. Content Script - Scripts that run in isolation in the context of the web page. Injected Script - Scripts that are programmatically injected into the web page.
A Chrome extension will typically consist of various cohesive parts or components, each with a different set of responsibilities. In order for all these components to work together, they communicate via messaging.
Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With