Reputation: 305
I have a content script with some data read form the content script //Manifest file
{
"manifest_version": 2,
"name": "Random App",
"description": "This App will do random stuff",
"version": "1.0",
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"content_scripts": [
{
"matches": ["https://www.youtube.com/*"],
"js": ["content.js"],
"run_at": "document_start",
"all_frames": true
}
],
"web_accessible_resources": ["InjectScript.js"],
"permissions": ["tabs", "background", "storage","https://www.youtube.com/*" ],
"browser_action": {
"default_title": "This is just a random app",
"default_icon": "hello.png"
}
}
//Content.js My requirement is to send firstParamTobeSent and secondParamTobeSent to InjectScript
var firstParamTobeSent = "Stackoverflow";
var secondParamTobeSent = "Stackoverflow2";
var s = document.createElement('script');
s.src = chrome.extension.getURL('InjectScript.js');
alert("got the URL on InjectScript");
s.onload = function() {
alert("1." + firstParamTobeSent + "----" + secondParamTobeSent);
this.parentNode.removeChild(this);
};
window.postMessage("YourName_expectedMessage"); //If I comment this line alert 1 and 2 start working.
alert("2." + firstParamTobeSent + "----" + secondParamTobeSent);
(document.head||document.documentElement).appendChild(s);
//InjectScript.js
window.addEventListener("message", function(request) {
alert("Reaching here = " + request.data + "ORGIN = " + request.origin);
if (request.data == "YourName_expectedMessage") //note that there are likely many script on the page or it's child frames that also send messages to this page, so you better name
{
alert("It works");
}
}, true);
Upvotes: 0
Views: 774
Reputation: 305
I finally used
s.onload = function() {
var evt=document.createEvent("CustomEvent");
evt.initCustomEvent("yourCustomEvent", true, true, { 'Data1' : 'Value1' , 'Data2' : 'Value2' });
document.dispatchEvent(evt);
...//Ur code
}
//Injected.js
document.addEventListener('yourCustomEvent', function (e)
{
d1= e.detail.Data1;
d2 = e.detail.Data2;
alert("received d1= " + d1 + "d2 = " + d2);
});
Upvotes: 1
Reputation: 4573
For messaging from content script to page script you can use this code:
window.postMessage("YourName_expectedMessage", "*")
.
On the page script (WebAccessibleResources.js) you should use
window.addEventListener("message", function(request) {
if (request.data == "YourName_expectedMessage") //note that there are likely many script on the page or it's child frames that also send messages to this page, so you better name your message so that is unique in the entire world.
{
...
}
}, true);
Alternatively, you can create tags on the page and store necessary data in the attributes of these tags, so that the other end can read them.
Upvotes: 0