我有一个内容脚本,其中包含从内容脚本中读取的一些数据 //清单文件
{
"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我的要求是将firstParamTobeSent和secondParamTobeSent发送到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);
答案 0 :(得分:1)
我终于使用了
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);
});
答案 1 :(得分:0)
对于从内容脚本到页面脚本的消息传递,您可以使用以下代码:
window.postMessage("YourName_expectedMessage", "*")
。
在页面脚本(WebAccessibleResources.js)上,您应该使用
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);
或者,您可以在页面上创建标签并将必要的数据存储在这些标签的属性中,以便另一端可以读取它们。