chrome extension: sharing an object between content scripts and background script

♀尐吖头ヾ 提交于 2019-12-21 10:15:58

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/13680985/chrome-extension-sharing-an-object-between-content-scripts-and-background-scrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!