3
votes

In my google chrome extension user clicks on link and than have to be automatically logged in on page.
Flow have to be like this: User click on link in GC Extension, script will take all required params and than send to newly opened tab.
There my script has to insert passed params and make some actions.
But I don't understand, how can I pass variables from GC extension script to newly opened tab?
Here is my manifest.json

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
 "content_scripts": [
    {
    "js": [ "window/content.js"],
    "matches": [
      "https://steamcommunity.com/login/home/?goto=",
      "http://steamcommunity.com/*",
      "https://steamcommunity.com/*"
    ]
   }
 ],
 "background": {
   "scripts": [
     "./scripts/back.js"
    ]
  },
 "web_accessible_resources": [
   "popup.js",
   "window/content.js"
 ],
"permissions": [
    "activeTab",
    "tabs",
    "<all_urls>",
    "cookies",
    "declarativeContent"
 ]


I've tried so far to use this in main.js:

chrome.tabs.executeScript(
   tab1.id,
      {code: "var test =" + test
       allFrames: true
      },
      {file: "../popup.js"}, )
    })

But when click performs, script open new tab, and execute everything I wrote, but don't see variable 'test'.

1
executeScript apparently uses just file when both file and code are specified. Use messaging or simply nest executeScript: the outer runs code, and in its callback the inner runs file. - wOxxOm
The scripts will execute in the scope of the extension, making it very difficult to write anything to the page. I'd recommend just using localStorage. Just bear in mind that this persists between sessions, which may be a pro or a con, depending on what you're trying to do. - Reinstate Monica Cellio

1 Answers

0
votes

It is not a hard, just a tricky: you need to append an inject code from the content-script.

Consider this example:

manifest.json

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "1.0.0",

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_end",
      "all_frames":false
    }
  ],

  "web_accessible_resources": [
    "inject.js"
  ]
}

content.js

var script = document.createElement('script'); 

script.src = chrome.extension.getURL('inject.js');
script.onload = function() {
    window.postMessage({ type: "FROM_MY_EXTENSIONS", value: "123" }, "*");
}

document.body.appendChild(script);

inject.js

window.addEventListener("message", function(event) {
    if(event.data.type === 'FROM_MY_EXTENSIONS') {
        window._test = event.data.value;
        console.log('_test:', _test);
    }
}, false);

This extensions will creates new _test variable in any tab with value from the content script message.