Reputation: 40681
I realized we can work at shared DOM (according to manual) from content scripts.
We can connect injected DOM content with our Content Scripts via
element.addEventListener('click',function(){ ourController.fnCallback(); });
// or
element.onclick = ourController.fnCallback;
But when injected DOM implements something like this:
<a href="javascript:ourController.fnCallback();">Click Me!</a>
thrown error is cannot call fnCallback() on undefined ourController
(not exactly rewritten error messages)
Is there aby way we can communicate with our javascript object from injected dom like i tried in second example?
Object is defined in content_script.js
like this:
var ourController = {
fnCallback: function(){
// code here
}
};
and this code is placed directly in script loaded according to manifest like this:
"content_scripts": [ {
"js": [ "content_script.js" ],
"matches": [ "http://*/*", "https://*/*", "ftp://*/*" ],
"run_at": "document_start"
}],
Upvotes: 0
Views: 1364
Reputation: 40681
Solution to this problem comes out from documentation:
Execution environment
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.
So any injected content is not able to work with content script. Only solution is to use code like this from withing content scripts
document.getElementById("elmID").addEventListener('click',function(){
var data = //get the data from DOM or window state, not from content script
chrome.extension.sendRequest({
'request_data': data
});
})
It will add click-event function which can communicate with content_script
Upvotes: 2