Neither the content_scripts nor the background have access to the variables and functions defined on the web page, since they are executed in an isolated environment.
In order to run the code in the context of a web page, you need to manifest.json the key web_accessible_resources in manifest.json . This key indicates which scripts can be executed in the context of a web page.
Add the key to manifest.json :
"web_accessible_resources" : ["lib/inject/script.js"]
From the content_scripts embed the code on the page:
var script = document.createElement('script'); script.src = chrome.extension.getURL("lib/inject/script.js"); document.head.appendChild(script);
From script.js you can perform actions in the context of a web page:
alert(current.oid);
In order to get the result of the work you need to define the key externally_connectable in manifest.json . The values of this key indicate which pages can communicate with the extension via runtime.connect and runtime.sendMessage .
Add the key to manifest.json :
"externally_connectable": { "matches": ["*://*.example.com/*"] }
Sending a message from the page:
// Идентификатор расширения, с которым нужно связаться var extensionId = "abcdefghijklmnoabcdefhijklmnoabc"; chrome.runtime.sendMessage(extensionId, {oid: current.oid});
In the extension, you need to set a listener for the onMessageExternal event:
chrome.runtime.onMessageExternal.addListener( function (request, sender, sendResponse) { if (request.oid) func(request.oid); });
This is not the only way. You can send data using DOM 's page or window.postMessage .
Web Accessible Resources | externally_connectable | Execution environment