I have a tab with, among other stuff, following content:
<meta http-equiv="refresh" content="0; URL='whatsoever'" />
I also have a plugin running that registers every tab using this technique:
chrome.tabs.onUpdated.addListener(doStuff);
The doStuff-function sends a message to the tab:
function doStuff(tabId, changeInfo, tab){
chrome.tabs.sendMessage(tabId, {'message': 'content'}, function(response){
doOtherStuff(response);
});
}
I have a script registered (not seen here), and in that script, this happens:
function receiveMessage(request, sender, sendResponse){
sendResponse({'content': 'responseData'});
}
chrome.extension.onMessage.addListener(receiveMessage);
My problem is that due to the instantaneous refresh, the response times out, and following error appears in the console:
Could not send response: The chrome.extension.onMessage listener must
return true if you want to send a response after the listener returns
(message was sent by extension XYZ).
Why is that, and how can I circumvent this issue? Thanks in advance.
It says, the function receiveMessage should exit with return true;. Only then the message will continue to be send. On false, it is aborted the moment the function returns. So add return true
see:
This function becomes invalid when the event listener returns, unless
you return true from the event listener to indicate you wish to send a
response asynchronously (this will keep the message channel open to
the other end until sendResponse is called).
from the doc:
https://developer.chrome.com/extensions/runtime#event-onMessage
function receiveMessage(request, sender, sendResponse){
sendResponse({'content': 'responseData'});
return true;
}
chrome.extension.onMessage.addListener(receiveMessage);
Related
In our firefox extension from the background script, we are checking the currently loading tab and check whether the URL is our desired URL if it is our desired URL then we are executing a javascript file on the tab with the help of browser.tabs.onupdated event using browser.tabs.executeScript and the file is executed successfully but the window.onload event present on the content script doesn't execute
but the console statement on the first line executed in the content script
Background.js
browser.tabs.onUpdated.addListener(
function (tabId, changeInfo, tab) {
// here checking wether to execute the script for the currently loading tab based on the URL of tab
browser.tabs.executeScript(tab.id, { file: "jquery.min.js" });
browser.tabs.executeScript(tab.id, { file: "automate.js" });
},
{ properties: ["status"] }
);
automate.js
console.log("automate.js executing");
window.addEventListener("load",function(){
// this console.log statement not printed
console.log("window is loaded");
})
By default content scripts run at document_idle:
The document and all its resources have finished loading.
Solution:
It is the same as load event conditions so you don't need it. Simply do what you need right away.
Alternative:
If for some reason you need to do something before the load event and something afterwards, you can use document_end to run the script at DOMContentLoaded event (DOM is ready, resources are still loading) or document_start (DOM is empty, only <html> node is parsed).
browser.tabs.executeScript(tab.id, { file: 'jquery.min.js', runAt: 'document_end' });
browser.tabs.executeScript(tab.id, { file: 'automate.js', runAt: 'document_end' });
I'm testing Pubnub 3.7.1. But I have a problem with the leave event trigger that doesn't fired.
I can only see the join and timeout trigger event. Here is some code that I use:
pubnub.subscribe({
channel: 'channel',
presence: manageUsers,
message: showMessage
});
function manageUsers(message, event, channel) {
console.log(message);
}
What could be the problem?
Thanks.
UDATE:
Another thing is when I enter in a channel where there are some people connected, I can't get their presence data. I can only get their presence data from new users.
Here is the example:
http://plnkr.co/edit/qlqhb677CZhTeR8Sa52x?p=preview
Your code works as expected.
When a user join, it triggers a 'join' action, and when the user goes idle, the action becomes 'timeout'.
The 'leave' action occurs when a user unsubcribe from the channel.
e.g.
byeButton.click(function(){
pubnub.unsubscribe({
channel : 'channel_1',
callback: function(m){
console.log(m.action); // should print 'leave'
}
});
});
See more at:
https://www.pubnub.com/docs/javascript/api/reference.html#unsubscribe
This question already has answers here:
Chrome Extension Message passing: response not sent
(3 answers)
Closed 8 years ago.
I'm working on a simple Chrome extension. I have something like that
/* content script */
chrome.runtime.sendMessage({msg: "marco"}, function(response){
if (response.foo){
console.log(response.foo);
}
});
/* background script */
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if (request.msg){
// sendResponse({foo: "polo"}); // works fine
// load a local JSON file
$.getJSON("path/to/file.js", function(data){
console.log("success"); // works fine
sendResponse({foo: "polo"}); // does not work
});
}
});
As you can probably see, the call to sendResponse from the body of getJSON's callback does not seem to be sending the response although the call to log right above it executes perfectly. If I call sendResponse from outside the body of getJSON's callback, it sends the response normally.
Any idea of what might be the problem?
In the end of the listener function you must return "true" so the connection to the content script will remain opened.
In async calls listener function will end and the port will be closed immediately so sendResponse function will do nothing.
From the documentation:
This function becomes invalid when the event listener returns, unless
you return true from the event listener to indicate you wish to send a
response asynchronously (this will keep the message channel open to
the other end until sendResponse is called).
I'm experimenting with the close event in Node.js. I'm very new to Node.js so I'm not sure if this is a decent question or a sad one.
Documentation for close event:
http://nodejs.org/api/http.html#http_event_close_2
I want to output to the console a message if the browser is closed before the end event is reached.
While the server ran and before it got to 15 seconds, I tried closing the browser and killing the process through Chrome Tools. No message is output to the console and if I open up other connections by visiting localhost:8080 with other windows, I quickly get a 'hello' indicating my node server thinks there are at least two connections.
I'm either not understanding how to kill processes in Chrome or how the event close works.
Or if End and Close are the same - node.js https no response 'end' event, 'close' instead? - why isn't my "They got impatient!" message still ouput in the console?
How can you output to a console if the process was ended before the event end was reached?
var http = require('http'),
userRequests = 0;
http.createServer(function(request,response){
userRequests++;
response.writeHead(200, {'Content-Type' : 'text/plain'});
if ( userRequests == 1 ){
response.write('1st \n');
setTimeout ( function() {
response.write('2nd Thanks for waiting. \n');
response.on('close', function() {
console.log("They got impatient!");
});
response.end();
}, 15000);
response.write('3rd \n');
}
else {
// Quick response for all connections after first user
response.write('Hello');
response.end();
}
}).listen(8080, function() {
console.log('Server start');
});
Thank you.
First - move the event handler for the close message outside the timeout function - you're not hooking up the close handler until after your timeout expires, and probably missing the event.
Second, you never decrement userRequests anywhere; shouldn't there be a userRequests--; line somewhere? This would be throwing off your logic, since it'll always look like there's more than one request.
I have created a chrome extension which does something after its button is clicked.
However I dont want it be abused so I need the its code to be executed after some time.
How can I surround this code with a timeout in order to achieve this?
Thank you for reading me!
chrome.tabs.getSelected(null,function(tab) {
var Mp=tab.url.substring(0,23);
if(Mp=='https://www.example.com')
{
onWindowLoad();
chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource")
{
...Working here
}
});
}
else
{
message.innerHTML='<span style="color: #f00">This is not a valid page</span>';
}
});
function onWindowLoad()
{
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {file: "getPagesSource.js"});
}
I had to make a compromise so just after the getSelected I added the following line:
chrome.browserAction.disable(tab.Id);
It disables the action button thus it cant be clicked while the script sends the data to the server, as with this extension I grab the tab url in order to store it in my database.
After the ajax response and adding the following
if(xhr.readyState==4)
{
message.innerHTML=xhr.responseText;
chrome.browserAction.enable(tab.Id); /////<---THAT LINE
}
the button gets ready again to be clicked.
I couldnt find the way to add a specific delay in seconds, this way seems stupid but its working, as the response's delay from my server is enough for switching the 2 states of the action button.
With this, however another problem came up, which Ill write in different question.