0

In my manifest.json i have

"content_scripts": [
    {
      "matches": [ "https://*/*", "http://*/*" ],
      "run_at": "document_start",
      "all_frames": true,
      "match_about_blank": true,
      "js": [ "run_on_every_page.js" ]
    }

In run_on_every_page.js

var yourCustomJavaScriptCode = 'document.pageVariable={I_want_variable_from background.js_to_be_inserted_here};';
var script = document.createElement('script');
var code = document.createTextNode('(function() {' + yourCustomJavaScriptCode+ '})();');
script.appendChild(code);
document.documentElement.appendChild(script);

How do i insert variable from background.js to "I_want_variable_from background.js_to_be_inserted_here"?

Background.js is:

var myVariable=Math.random();//Dynamic variable that changes based on user activity
Phantom
  • 11
  • 1
  • 2
  • In Chrome it's [convoluted](https://stackoverflow.com/a/45105934). In Firefox you can use browser.contentScripts API. – wOxxOm Mar 12 '19 at 15:05
  • Thank you for your link, but it will eventually pollute all cookies =/ Can't believe it is the only way... but looks like it. – Phantom Mar 12 '19 at 16:24
  • Why would it pollute all cookies? You can use just one value with a name like 'foo' + chrome.runtime.id. Also you can immediately remove it. – wOxxOm Mar 12 '19 at 16:28
  • I maybe missing something, but imho - it will be like you said in the world with one page with nothing but "hello world" in it. In the real life with pages having dozens of images and scripts and Ajax requests, all running simultaneously, removing that cookie isn't really an option. – Phantom Mar 13 '19 at 03:17
  • What does ”pollute all cookies” actually mean? You can set the cookie path to the page path so it won't be included with the requests to resources. You can remove the cookie in your content script immediately. You can use the same cookie name everywhere. – wOxxOm Mar 13 '19 at 04:37
  • "You can set the cookie path to the page path so it won't be included with the requests to resources" - Thank you! Although that trick won't work for the iframes without src, but it is a viable solution! – Phantom Mar 13 '19 at 19:02

0 Answers0