May i use sendResponce/onMessage within event page? (bug?) - javascript

Seems like i can send message, but can't receive response. Everything works fine when i use sendMessage from another context (popup, content script, etc).
Is it bug?
event-page.js
(function (chrome, undefined) {
'use strict';
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
console.info('onMessage: ' + message.method);
switch (message.method) {
case 'withResponseAsync':
setTimeout(function () {
sendResponse({some: 'response'});
}, 1000);
return true;
break;
case 'withResponse':
sendResponse({some: 'response'});
break;
}
});
var showResponse = function (response) {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
console.info(response);
};
// ok. onMessage: noResponse
chrome.runtime.sendMessage({method: 'noResponse'});
// fail. Could not establish connection. Receiving end does not exist.
chrome.runtime.sendMessage({method: 'withResponse'}, showResponse);
// fail. Could not establish connection. Receiving end does not exist.
chrome.runtime.sendMessage({method: 'withResponseAsync'}, showResponse);
})(chrome);

Related

How to pass Data between files Chrome Extension?

Currently, I mainly work with two files, background.js and popup.js.
In background.js
I have a bunch of functions that let me store data in an IndexedDB. And in popup.js I call the functions like this:
chrome.runtime.sendMessage({
message: "insert",
payload: [
{
url: form_data.get("message"),
text: form_data.get("message"),
},
],
});
Depending on the message, a certain function is called. When the function has successfully executed I do this from the background.js file:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "insert") {
let insert_request = insert_records(request.payload);
insert_request.then((res) => {
chrome.runtime.sendMessage({
message: "insert_success",
payload: res,
});
});
});
This is my problem:
How do I send data from background.js to popup.js. What I want is to get the URL of the current page, and then send it to popup.js and store it in the Database.
I have already looked at already existing posts, but none of them really helped.
Can someone please help me out.
Update
Currently I use this is in background.js to get the current URL. It works just fine. But how can I pass the tab.url to my popup.js file?:
let activeTabId, lastUrl, lastTitle;
function getTabInfo(tabId) {
chrome.tabs.get(tabId, function (tab) {
if (lastUrl != tab.url || lastTitle != tab.title)
console.log((lastUrl = tab.url), (lastTitle = tab.title));
});
}
chrome.tabs.onActivated.addListener(function (activeInfo) {
getTabInfo((activeTabId = activeInfo.tabId));
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (activeTabId == tabId) {
getTabInfo(tabId);
}
});

Rendering reCaptcha V2.0 widget within Marionette Itemview

This will be a post where I ask the question and propose a solution
Since having had several trouble and having looked around a lot I decided to post my final solution for anyone else to take profit from it.
Question:
How to render google's reCaptcha v2.0 widget and verifying it in a Marionettejs app with a java back end.
After the common steps and following google guides to render the re captcha my captcha still didn't render, so here comes my solution:
Rendering the captcha and the inclusion of the script are both made inside the itemview onRender function:
'text!login/templates/form.html',
'app'
], function (app, Marionette, Backbone, _, $, Handlebars, FormTemplate) {
return Marionette.ItemView.extend({
template: Handlebars.compile(FormTemplate),
ui: {
form: '
},
events: {
'submit #ui.form': 'onSubmit'
},
onRender: function() {
this.loadCaptcha();
},
loadCaptcha: function() {
var self = this;
var getRecaptchaResponse = function(response) {
self.captchaResponse = response;
};
window.renderCaptcha = function () {
self.captchaWidgetId = grecaptcha.render('yourCaptchaDiv', {
sitekey: 'YourSiteKey',
callback: getRecaptchaResponse
});
};
$.getScript('https://www.google.com/recaptcha/api.js?onload=renderCaptcha&render=explicit', function() {});
},
...
}
I tried other ways of loading the script with several errors, like the script loaded before the div for it, or the browser says de Dom has completely loaded but the onRender gets called after
I had to include a div for the captcha widget to load in, this is in
form.html
<div id="reCaptcha" class="btn"></div>
That will have your widget rendered, now you need to both verify it has been filled and it is a valid user response with google, for this I use the same module and use the next function:
onSubmit: function (e) {
//only act if the captcha has been filled - This could be easily erased from a browser, but a back end verification takes place too
if (grecaptcha.getResponse() !== "") {
e.preventDefault();
var _view = this;
this.blockForm();
$.ajax({
url: 'yourLoginService',
type: 'POST',
data: {
userLogin: this.ui.user.val(),
userPassword: this.ui.password.val(),
//get the captcha response
captchaResponse: grecaptcha.getResponse()
}
}).done(function (data) {
app.router.navigate('', {trigger: true});
_view.destroy();
}).fail(function (jqXHR, textStatus, errorThrown) {
// your fail handling
});
}
},
Then comes the time to verify your captcha server side using the secret key provided by google (note this is a Java6 app, therefore the clumbersome exception Handling):
//some other imports ignored
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
class Captcha {
private static final String CAPTCHA_SECRET_KEY = "YourSecretKey";
private static final Logger LOGGER = Logger.getLogger(Captcha.class);
static boolean isCaptchaValid(String response) {
try {
String url = "https://www.google.com/recaptcha/api/siteverify?"
+ "secret=" + CAPTCHA_SECRET_KEY
+ "&response=" + response;
InputStream res = new URL(url).openStream();
JSONObject json = new JSONObject(getJsonResponse(res));
res.close();
return json.getBoolean("success");
} catch (JSONException e) {
LOGGER.error("Can not parse captcha response Json: " + e);
return false;
} catch (MalformedURLException e) {
LOGGER.error("Malformed URL: " + e);
return false;
} catch (IOException e) {
LOGGER.error("Error reading response from captcha verification response: " + e);
return false;
}
}
private static String getJsonResponse(InputStream res) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(res, Charset.forName("UTF-8")));
/*TODO in java 8+ use this and avoid using the external library
return rd.lines().collect(Collectors.joining());
*/
return IOUtils.toString(rd);
}
}

Sinon stub callFake function not replacing original function

So this is the (snipped) code for a chatbot. I want to override the sendMessage() function to just echo the message argument. In this case, the original function runs and gives an error at the 2nd line of the function. Obviously, modules aren't loaded and I don't need them to. This is a test for the eventHandler to echo the right messages. Ideas?
var modules = require('./modules');
console.log('[tose] Loading modules: ', Object.keys(modules));
function eventHandler(channel, type, data, react=()=>{}) {
switch (type) {
case 'new_message':
console.log('[tose][new_message]', channel, 'from:', data.cid, 'message:', data.message);
if (regexTemplates.testSearch.test(data.message.toLowerCase())) {
...
} else {
sendMessage(channel, data.cid, data.message); // Basic echo message
}
break;
}
}
// The function to be stubbed
function sendMessage(channel, cid, message) {
console.log('[tose][send_message]', channel, 'to:', cid, 'message:', message);
coms[channel].sendMessage(cid, message); // Getting error here thus not really stubbed
}
exports.eventHandler = eventHandler;
exports.sendMessage = sendMessage
And the test:
describe('Tose core', function() {
describe('Process messages', function() {
before(function() {
var stub = sinon.stub(tose, 'sendMessage').callsFake(function(channel, cid, message) {
assert.equal(message, 'Test message');
return message
});
});
after(function() {
tose.sendMessage.restore();
});
it('should echo messages', function() {
var data = {message: 'Test message'}
tose.eventHandler('test', 'new_message', data)
assert(tose.sendMessage.calledOnce);
});
});
});
The problem here is that when you use Sinon to stub an object's function, you're stubbing that (and only that) object's function.
Your code (the first code block) is using the local definition of the sendMessage function.
When you stub the tose object (in the second code block), you are changing the sendMessage function thats on the tose object and not the local definition of the function.
There are many different ways you could approach this, one of which is:
var modules = require('./modules');
var functions = {
eventHandler: eventHandler,
sendMessage: sendMessage,
};
console.log('[tose] Loading modules: ', Object.keys(modules));
function eventHandler(channel, type, data, react=()=>{}) {
switch (type) {
case 'new_message':
console.log('[tose][new_message]', channel, 'from:', data.cid, 'message:', data.message);
if (regexTemplates.testSearch.test(data.message.toLowerCase())) {
...
} else {
functions.sendMessage(channel, data.cid, data.message); // Basic echo message
}
break;
}
}
// The function to be stubbed
function sendMessage(channel, cid, message) {
console.log('[tose][send_message]', channel, 'to:', cid, 'message:', message);
coms[channel].sendMessage(cid, message); // Getting error here thus not really stubbed
}
module.exports = functions;
Note: functions is not a descriptive name - feel free to change it to something that is more meaningful.

Multiple messages in a single function call to chrome.runtime.sendMessage();

chrome.runtime.sendMessage();
I want to pass multiple (to be specific 2) messages from my contentscript.js to popup.js.
I don't need other arguments for this function, I only need the message argument.
In my contentscript.js I have this:
chrome.runtime.sendMessage(message1);
chrome.runtime.sendMessage(message2);
Here is my popup.js:
chrome.runtime.onMessage.addListener(function(messsage1){
//code for handling the message
});
chrome.runtime.onMessage.addListener(function(messsage2){
//code for handling the message
});
I want to combine these two functions into a single function and handle the messages like:
chrome.runtime.onMessage.addListener(function(){
// how to write the parameter for this function, I can't use ',' right?
// code for handling the message1, message2
});
How can I do this?
I would send the messages as JSON objects, with an additional property to specify which type of message it is. For example:
chrome.runtime.sendMessage({content: "Message1", type: "m1"});
chrome.runtime.sendMessage({content: "Message2", type: "m2"});
And then you can combine the message listener into one function:
chrome.runtime.onMessage.addListener(function(message) {
if(message.type == "m1") {
console.log("First message: ", message.content);
}
if(message.type == "m2") {
console.log("Second message: ", message.content);
}
}
Of course this is just a rough example - you should tailor the structure of the JSON objects to your extension's requirements, but this is the pattern that I would use.
contentscript.js
chrome.runtime.sendMessage({
greeting: "message1"
})
chrome.runtime.sendMessage({
greeting: "message2"
})
popup.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.greeting == "message1") {
//action 1
} else if (request.greeting == "message2") {
//action 2
}
});
API: http://developer.chrome.com/extensions/messaging
runtime.sendMessage can be used only for one-time requests as per documentation. Consider using tabs.connect instead.
This is the code for the extension page to connect to your tab:
var port = chrome.tabs.connect(tab.id);
port.postMessage({type: "first", content: "Hi!"});
port.postMessage({type: "second", content: "How are you?"});
And this code should be specified in the content script:
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
if (msg.type == 'first') {
...
}
if (msg.type == 'second') {
...
}
});
};

Extjs 3.3 IE8 chained events is breaking

This one is wired.
This fires from a grid toolbar button click:
// fires when the client hits the add attachment button.
onAddAttachmentClick: function () {
var uploadAttachmentsWindow = new Nipendo.ProformaInvoice.Attachment.UploadWindow({
invoice: this.invoice,
maxFileSizeInMB: this.maxFileSizeInMB
});
uploadAttachmentsWindow.on('uploadcomplete', function (win, message) {
if (message.msg !== 'success') {
return;
}
win.close();
var store = this.getStore();
store.setBaseParam('useCache', false);
store.load();
this.fireEvent(
'attachmentuploaded',
this.invoice.ProformaInvoiceNumber,
this.invoice.VendorSiteID,
this.invoice.CustomerSiteID);
}, this);
uploadAttachmentsWindow.show();
} // eo onAddAttachmentClick
This is what happens on the uploadcomplete event:
this.uploadBtn.on('click', function () {
var form = this.uploadForm.getForm();
if (!form.isValid()) {
return;
}
form.submit({
url: 'XXX.ashx',
waitMsg: Nipendo.Localization.UploadingAttachment,
scope: this,
success: function (form, action) {
this.fireEvent('uploadcomplete', this, {
msg: 'success',
response: action.response
});
},
failure: function (form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
this.fireEvent('uploadcomplete', this, {
msg: 'Form fields may not be submitted with invalid values'
});
break;
case Ext.form.Action.CONNECT_FAILURE:
this.fireEvent('uploadcomplete', this, {
msg: 'Ajax communication failed'
});
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert(action.result.title, action.result.message);
this.fireEvent('uploadcomplete', this, {
msg: action.result.message
});
break;
}
}
});
}, this);
On IE 8 I am getting this error in the debugger:
I have no idea what object is missing... from my check they are all defined.
Any idea anyone?
Notice that I have an event firing from a listener (I am suspecting it to be the root of the problem).
It is hard to see but the error occuers in ext-all.js in the fire method.
I have found the answer in : https://stackoverflow.com/a/3584887/395890
Problem was I was listing to events is 2 different windows, that is not possible in Ext.
What I have done to solv it was to call the opner window from the pop up window to notify about changes.

Categories

Resources