user12669123
user12669123

Reputation:

Chrome Extensions Message Passing Data from popup.js to content scripts

I have developed a chrome extension that in the popup has a dependant drop down. Based off the users selection in this drop down an ajax call is made to get some data based off the if of the selected option. To so this I have written this jquery which works correctly and returns the chosen options id.

$('#scenarioDropdownList').change(function () {
    scenarioId = $('#scenarioDropdownList option:selected').prop('id');
    });

The ajax call takes the scenarioId as a parameter and returns data with the matching scenarioId. I am then using this data to manipulate fields in the DOM. Because of this my content script is as follows, which includes the ajax call to get the data and then some logic which sues the data.

As i am developing a chrome extension the drop down is in the popup.html so the jquery to get the id (see first part of code) is in the popup.js. I need to be able to pass the scenarioId from the popup.js to the content script so that it can be used in the ajax call.

I have read up on message passing and procided the following:

popup.js

$('#scenarioDropdownList').change(function () {
            scenarioId = $('#scenarioDropdownList option:selected').prop('id');
            chrome.runtime.sendMessage(scenarioId);
            });

content script (content.js)

chrome.runtime.onMessage.addListener(function(response, sender, sednResponse) {
    var getScenarioId = response;
})

Unfortunately this is not working as of yet as I am struggling to produce a solution that will work and pass the scenarioId from then popup.js to the content script so that it can be used.

FYI I receive no error with the code I have produced for the message passing.

Upvotes: 0

Views: 804

Answers (1)

user12669123
user12669123

Reputation:

After some various attempts at solving my issue I came up with the following which works. Currently it is quite simple. I can improve this by adding in a response message etc.. but for what I desire this functionality is suitable.

Popup.js

 $('#scenarioDropdownList').change(function () {
            scenarioId = $('#scenarioDropdownList option:selected').prop('id');


            // Here I pass the message to the content script with the actual content being the result of the variable scenrioId.
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, scenarioId)
              });
        })

Content Script (content.js)

chrome.runtime.onMessage.addListener(function(request) {
    console.log(request.scenarioId);  
      return true; // Ensures it is async

Currently I am just logging the result to the console, but i am going to implement it so that i can use it elsewhere.

Upvotes: 1

Related Questions