T
T
ThreegunD2016-11-14 00:13:20
JavaScript
ThreegunD, 2016-11-14 00:13:20

How to pass variables to injection script?

The code is running in the background

//Открытие сайта в новой вкладке
window.open("google.ru");
//Вставка кода в активную вкладку и последующая отправка на внедрённый скрипт значения
chrome.tabs.executeScript({code:" document.createElement('script');script.src = chrome.extension.getURL('lib/inject/script.js');document.head.appendChild(script); "});

chrome.tabs.query({}, function(tabs) {
      for (var i = 0; i < tabs.length; i++) {
        chrome.tabs.sendMessage(tabs[i].id, {
          command : "extEvSettingsUpdate"
        });
      }
    });

The lib/inject/script.js script itself
chrome.extension.onMessage.addListener(function(request, sender, callback){
    if (!!request && !!request.command) {
        if (request.command === "extEvSettingsUpdate") {
            console.log("Принято!");
        }
    }
});

This script throws the error Cannot read property 'onMessage' of undefined
What's the problem?
How to pass value from background.js to inline script (lib/inject/script.js)?
Manifesto
{
  "name": "Test",
  "description": "1234567890",
  "externally_connectable": {
      "matches": [ "https://*.google.com/*", ]
   },
  "version": "0.1",
  "manifest_version": 2,
  "icons":{
  "128":"icons/red.png"
  },

  "browser_action": {
      "default_title": "ThisIsGooood",
      "default_icon": "icons/red.png",
      "default_popup": "popup.html"
    },

  "background": {
    "page":"background.html"
  },
  "web_accessible_resources" : ["lib/inject/script.js"],
"permissions": [
    "*://google.com/*",
    "tabs",
    "background" ,
    "storage",
    "alarms",
    "notifications",
    "activeTab",
    "webRequest",
    "webRequestBlocking"
  ]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2016-11-14
@ThreegunD

How to properly notify content scripts about changes in browser extension settings?
#1UPD Remove
this line:

//Вставка кода в активную вкладку и последующая отправка на внедрённый скрипт значения
chrome.tabs.executeScript({code:" document.createElement('script');script.src = chrome.extension.getURL('lib/inject/script.js');document.head.appendChild(script); "});

Add this to the manifest:
"content_scripts": [{
  "all_frames": false,
  "matches": ["*://*/*"],
  "js": ["lib/inject/script.js"],
  "run_at": "document_end"
}],

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question