Got a bit of an unusual situation. I’m using select2 in a Chrome extension. A Chrome extension has access to a JS file which is sandboxed from the internet. But it can get data from the internet by passing messages back and forth with a privileged JS file using some asynchonous message-passing methods that Chrome exposes to extensions.
Here’s how I’ve set up my sandboxed JS file which interacts with the Chrome Extension’s DOM:
- In the ajax.transport callback I add a Listener for messages sent from the unsandboxed JS file (
port.onMessage.addListener
) - When this listener receives a message, it calls
$("#customer").select2({data: msg.response["results"]}).trigger('change');
- In
ajax.transport
I also send a message (port.postMessage
) with the value of the text typed into S2 - This message is sent to the unsandboxed JS file, hits a URL, gets the results, and sends a message that the listener in #1 is listening for.
I’m doing it this way because both the messages sent between the sandboxed and unsandboxed files are async, so we need a way to make sure the data gets passed back and forth.
This works the first time I run it, but subsequent runs don’t work. Any ideas why?
Sandboxed JS file:
$(document).ready(function() {
$("#customer").select2({
ajax: {
delay: 250,
transport: function(params, success, failure) {
port.onMessage.addListener(function(msg, sender) {
$("#customer").select2({data: msg.response["results"]}).trigger('change');
});
port.postMessage({q: params.data.q});
}
}
});
});
JSON:
{
"results":[
{
"id":1,
"text":"John Smith"
},
{
"id":2,
"text":"Sally Smith"
},
{
"id":3,
"text": "Chris Jones"
}
]
}
Video:
In this video the initial call with sm
finds the first two results. But the subsequent call with ch
returns no results:
Feels like I’m missing something obvious. Any ideas?
Thanks in advance!