I'm unable to pass messages between a trusted page-worker script, and the addon.
main.js:
var pageWorkers = require("sdk/page-worker");
var self = require("sdk/self");
// Create a page worker that loads Wikipedia:
pageWorkers.Page({
contentURL: self.data.url("html/worker.html"),
onAttach: function(worker) {
console.log("within onAttach");
worker.port.on("message", function() {
console.log("Message received");
});
worker.port.on("message", function(message) {
console.log("Message received1");
});
},
onReady: function(worker) {
console.log("within onReady");
worker.port.on("message", function() {
console.log("Message received");
});
}
});
worker.html:
<html>
<head>
<script src="../js/worker.js"></script>
</head>
<body>
</body>
</html>
worker.js:
console.log("trying to emit message");
addon.port.emit("message");
addon.port.emit("message", "value");
console.log("tried to emit message");
In main.js, If I try the following outside of the pageWorkers.Page() call:
pageWorkers.port.on("message", function() {
console.log("Message received");
});
I get the following exception:
Message: TypeError: pageWorkers.port is undefined
Any help would be appreciated. I have tried using postMessages to no avail. If asked, I can add that code also.
Page workers, like tab attaching and unlike pageMods, don't have an onAttach function. Nor do they have an onReady, since the contentScriptFile is automatically attached when the HTML is ready.
main.js
var worker = pageWorkers.Page({
contentURL: self.data.url("html/worker.html")
});
worker.port.on("message", function() {
console.log("Message received");
});
//If your events have the same name then they're the same event,
//irrespective of arguments passed
worker.port.on("message1", function(message) {
console.log("Message received1");
});
worker.js
console.log("trying to emit message");
addon.port.emit("message");
console.log("trying to emit message1");
addon.port.emit("message1", "value");
Related
I am trying to communicate with a google chrome extension using JavaScript. I have succeeded in calling the extension from my code. But can't read the response back to my application.
I have written the calling function like this.
function extensionCall(){
var event = document.createEvent('Event');
event.initEvent('EXTENSION_READ_EVENT');
document.dispatchEvent(event);
}
And the code inside the extension is
document.addEventListener("EXTENSION_READ_EVENT", function (data) {
chrome.runtime.sendMessage("test", function (response) {
});
});
chrome.extension.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action == 'EXTENSION_DATA') {
try {
readExtension($.parseJSON(msg.response));
}
catch (e) {
var error = "error" + e;
}
}
});
And I am expecting the response here..
function readExtension(val){
console.log(val);
}
But unfortunately, I am not getting any response from the extension.
How can I access the data to my application?
I created long-lived connection between popup and content pages. It works successfully. But I want to send message to content when user click the button.
contentscript.js
console.log("content script loaded!");
var port = chrome.runtime.connect({name: "content-script"});
port.onMessage.addListener(function(message){
if(message.key=="color"){
document.body.style.backgroundColor='lightgrey';
}
else if(message.key=="color2"){
document.body.style.backgroundColor='blue';
}
});
popup.js
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('btnStart');
checkPageButton.addEventListener('click', function() {
GetImages("");
}, false);
}, false);
function GetImages(pageURL){
if(activePort!=null){
activePort.postMessage({key:"color2"});
}
}
var activePort=null;
chrome.runtime.onConnect.addListener(function (port) {
console.assert(port.name == "content-script");
activePort=port;
port.onMessage.addListener(function(message) {
if(message.key=="download"){
port.postMessage({key:"download", text: "OK"});
}
else if(message.key="load"){
port.postMessage({key:"color"});
console.log(message.text);
}
})
});
In the GetImages() function I try to
port.postMessage({key:"color2"});
naturally it can't find the "port". So I create the activePort variable and try to post message with it. But It didn't work properly.
I changed the codes below and it works correctly. Now I opened the port in popup.js and I can send message with button click.
newpopup.js
function GetImages(pageURL){
port.postMessage({text:"ok"});
}
var port;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
port = chrome.tabs.connect(tabs[0].id,{name: "knockknock"});
});
newcontentscript.js
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
console.log(msg);
});
});
I was given a javascript function that I need to inject into a page in order to get a list of values that would be used later on. I can call this function directly on the webpage using the Chrome console but I want to replicate what I did in the Chrome console in nightmareJS on the webpage that is currently loaded.
This is the function:
function getList() {
require(['Service/List'],
function (Service)
{
Service.getList
({
onComplete: function (listOfServices)
{
console.log('List:success:' + JSON.stringify(listOfServices));
},
onFailure: function (error)
{
console.log('List:error:' + error);
}
});
});
}
getList();
I've tried injecting the file but I have had no success, I've also tried adding additional code to that function to write the output to a file but I do not think its being called at all.
Here is the nightmareJS
describe('Open login page', () => {
it('Login', done => {
nightmare
.goto('http://loginURL.com')
.wait('input[type="text"]')
.wait('input[type="password"]')
.insert('input[type="text"]', 'username')
.insert('input[type="password"]', 'password')
.click('input[type="submit"]')
.evaluate(function() {
nightmare.inject('js', 'getList.js' )
})
//.inject('js', 'getList.js' )
.then(function() {
console.log('Done');
})
})
})
})
This is the sample output after injecting the javascript file into the page:
List:success:"Test":"https://someURL.com/resource/test","Design":"https://someURL.com/resource/Design"},"NewSpace":"https://someURL.com/resource/NewSpace","Generator":"https://Generator.someURL.com/resource/test","SomethingElse":"https://someURL.com/SomethingElse/test","Connection":"https://someURL.com/Connection/test","WorldWide":"https://someURL.com/resource/WorldWide","Vibes":"https://Vibes.someURL.com/resource/test","GoogleSearch":"https://someURL.com/resource/GoogleSearch",
I want to be able to get that output from calling the javascript file on the page and save it to a file so that I can use it later to call other services in that list.
You can read the local javascript files that needs to be injected:
var fileData = [];
fileData.push(fs.readFileSync(path.resolve('../getList.js'), 'utf-8'));
It can be loaded into head section of the page via code:
browser.win
.evaluate(function(fileData) {
var elem = null;
for(var ii=0;ii<fileData.length; ii++ ) {
elem = document.createElement('script');
if (elem) {
elem.setAttribute('type', 'text/javascript'); //elem.src = localjs;
//console.log(fileData[ii]);
elem.innerHTML = fileData[ii];
document.head.appendChild(elem);
}
}
console.log("Testing loaded scripts");
console.log(getList());
return "Injected Scripts";
}, fileData)
.then(function(result) {
console.log(result);
}).catch(function(error) {
console.log("Load Error: ", error);
});
So on subdomain of my domain I have a html file, for example called file.html, which also includes <script src="https://example.com/script.js"> in itself.
Then, this script.js has some listeners connected with this html, and also the function to send messages to parent, which look as follows:
v.sendMessageToParent = function (message) {
var jsonMessage = {
action: message
};
var win = window.frames.target;
win.postMessage(jsonMessage, '*');
};
v.sendActionMessageToParent = function (action) {
var jsonMessage = {
action: 'action',
type: action
};
var win = window.frames.target;
win.postMessage(jsonMessage, '*');
};
Then, on another domain I have an iframe, which src is file.html.
This another domain also has some <script src="example.com/main.js">, and I need this main.js to listen to messages sent from script.js.
In main.js I have this code:
if (window.addEventListener) {
window.addEventListener("message", messageHandler);
} else {
window.attachEvent("onmessage", messageHandler);
}
function messageHandler(event) {
console.log(event.data);
}
But I don't get anything. No JS, domain or other errors are shown, just silence in console.
Where am I wrong?
Probably you forgot to name your iframe "target":
<iframe src="http://target.com" name="target">
<script>
var win = window.frames.target;
win.postMessage("message", *);
</script>
I am trying to implement an HTML5 WebWorker and I am using rails 3. I have this in my js code:
//When body(DOM) is ready
$(function() {
....
..
//test html5 webworkers
$('#test_html5_workers').click(function() {
var worker=new Worker('play.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
});
..
....
)};
and in another file I have this (in play.js)
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
I am currently getting this error:
Script file not found: play.js
I have tried other file path names with no luck.
Any ideas why I am getting this since both files are in the same directory, assets/javascripts?
I am using Firefox 17.0.1
The javascript file (play.js) should go in the public folder, or at least that's what I did to get it working.
This works on mine.
(function() {
//test html5 webworkers
$('#test').on('click', function(){
if(window.Worker){
var worker = new Worker('test.js');
worker.onmessage = function(e){
alert('worker said: ' + e.data);
}
worker.postMessage('start');
}
});
})();
//test.js
self.onmessage = function(e){
if(e.data === 'start'){
self.postMessage('booyeah');
}
}