"Troubleshooting: Issues with message passing between popup.html and content.js in Chrome Extension

I'm facing a challenge in creating an Extension that transfers data from popup.html to the tab dome. Unfortunately, I am having trouble with getting the sendMessage function to work and I can't figure out why. I'm using the following guideline as my reference: https://developer.chrome.com/extensions/messaging.html

Below are the sources I am working with:

manifest:
{
   "manifest_version": 2,
   "name": "OMG Campaign Preview Maker",
   "description": "Easy OMG Campaign Preview Maker",
   "background": {  "scripts": ["background.js"]},
   "version": "0.1",
   "content_scripts": [
        {
          "matches": ["http://*/*", "https://*/*"],
          "js": ["jquery-1.7.min.js", "content.js"]
        }
    ],
   "browser_action": {
      "default_icon": "logo_128.jpg",
      "popup": "popup.html",
      "default_popup": "popup.html"
   },
   "icons": {
      "128": "logo_128.jpg"
   }
}

popup.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<h1>Clicks</h1>
<p>extra1:
  <input type="text" name="extraclicks[]" id="extra1">
  <br>
  extra2:
  <input type="text" name="extraclicks[]" id="extra2">
  <br>
  extra3:
  <input type="text" name="extraclicks[]" id="extra3">
  <br>
  <br>
  <input type="submit" name="sendclicks" id="sendclicks" value="Invia Clicks">
</p>
</body>
</html>

popup.js

function sendClicks(){
    console.log("popup.js > sendClicks()");
    var clicksArr = new Array();

    $("input[name='extraclicks\\[\\]']").each(function(i, value){
        clicksArr.push($(this).val());
    });

    chrome.tabs.getSelected(null, function(tab) {
        console.log("popup.js > tab id: "+tab.id)
        chrome.tabs.sendMessage(tab.id, {type:"clicks" },
            function(response) {
                console.log(response.msg);
            }
        );
    });
    console.log("Has it been sent?");
}

$(function(){
    console.log("popup.js > OMD Extension ready");
    $('#sendclicks').click(function(){sendClicks();});
});

content.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("content.js > onMessage");

    if (request.type == 'clicks') {
        console.log("content.js > clicks");
        sendResponse({msg: "success"});
    }
});

Even though I can see the logs generated by popup.js in the console perfectly, I am unable to see any of the logs triggered by content.js. What could be the mistake I am making?

Answer №1

Whoops, it appears you accidentally sent a message to popup.js itself...

The getSelected function in popup.js monitors the activity of the popup tab (which is also a tab in Chrome), so the tab id actually refers to the popup tab and not the tab where your content.js is inserted.

By the way, getSelected is deprecated. Have you considered trying alternative methods? Check out http://developer.chrome.com/extensions/tabs.html#method-getCurrent for more information.

Answer №2

Wow, I can't believe I missed that... the issue was actually with the inspector page I had open. The "console.log" in content.js is outputting to the TAB INSPECTOR CONSOLE and not the extension console!

I'm sharing this in case it helps someone else.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble confirming the password field with regular expressions in angular.js

I'm trying to validate my password field with specific special characters requirements. The field must contain at least one number, upper case letter, lower case letter, and an underscore, all of which are mandatory. I have attempted to achieve this u ...

Performing a modulo operation within a v-for loop

I'm showcasing divs in a loop and I need to assign classes based on the loop index. My goal is to have index 0 and 1 with the class col-6, then indexes 2,3,4 with the class col-4, followed by index 5 and 6 having the class col-6, and so forth. This w ...

Creating a JavaScript-powered multi-department form: A step-by-step guide

Is there a way to maintain the form displayed on a webpage created in HTML5 and JavaScript for logging calls across three different departments? With buttons assigned to each department, clicking on them reveals the respective HTML form. That said, every t ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

Ajax encountered an error while attempting to load the requested resource

jQuery('input').on('click',function(e){ $.getJSON( "/data.json", function(info){ var name = data.name; } ); }); Every time we click, a JSON request is supposed to be made. But unfortunately ...

What is the best way to create transitions for item entry and exit in ReactJS without relying on external libraries?

I am looking to create an animation for a toast notification that appears when a user clicks on a button, all without the use of external libraries. The animation successfully triggers when the toast enters the screen upon clicking the button. However, I e ...

What strategies and techniques should be considered when creating websites optimized for mobile devices?

With a wealth of experience in programming languages like Java, Python, and C, I actively engage in self-study to enhance my skills. While I have dabbled in creating mobile-friendly websites, upon reviewing my work, it is evident that my frontend developme ...

What is the best way to include query parameters in form data within a Rails link_to instead of tacking them onto the URL?

I am facing an issue with my page that displays transaction search results. I have a search filter based on the "Token" column and when clicked, the search criteria should be set, and the search params should be passed as form-data in a POST method. Howeve ...

Why does Axios keep timing out despite successful testing in Postman?

Trying to set up a single request for my app using axios with express/node js. Here is the code snippet that was generated through the Postman app. I have attempted different variations by creating my own form, but I always end up with the same result. co ...

Tips on incorporating the wait function within the evaluation_now action in Nightmare?

While I am incorporating Nightmare actions in my script, a question arises regarding the use of the wait function within the evaluate_now function. How can I utilize the wait function within the evaluate_now function? I am aware that I can simply use the ...

When consecutive DOM elements are hidden, a message saying "Hiding N elements" will be displayed

Provided a set of elements (number unknown) where some elements should remain hidden: <div id="root"> <div> 1</div> <div class="hide"> 2</div> <div class="hide"> 3</div> <div class="hide"&g ...

Conceal a section if the array is not defined

Hey there, I've got this piece of code for checking the status of a Twitch streamer. $(document).ready(function () { // some initializations here var login = ''; var twitchStatusLinks = $('.twitch-status'); var twitchStatus ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...

The dropdown menu is not able to retrieve information from the secondary database

I have been encountering multiple challenges while working on a web-based dynamic form that I am developing. My current major issue is with populating the second #bodytype dropdown based on the selection made in the first, #bodyman, dropdown. Subsequently ...

What is the best way to generate a variable amount of div elements with constantly changing content using Angular2?

I'm not entirely sure on the process, but I believe ngFor would be used in this scenario. Essentially, my goal is to generate the following div multiple times, with each iteration updating the value inside the brackets from 0 to 1, 2, and so forth... ...

Refresh Google Maps without showing gray areas on the screen

Currently, I am utilizing the Google Maps API v3 in javascript and frequently reloading the map using an app.get while also incorporating layers and bookmarks via mongodb. Whenever I reload the map to erase everything, a gray background appears in the div ...

AngularJS is encountering an issue with the callback function, resulting in an error

Currently, I am utilizing the $timeout service in Angular to decrease a variable from 100 to 1 in increments of 1/10 seconds. Although I understand that using the $interval service would be a simpler solution, for this particular scenario, I am focused on ...

The AJAX request to the REST service is failing to trigger the success function in the AJAX call

Struggling with some issues related to AJAX, specifically when calling a Java REST server that I've developed. While I am relatively new to AJAX, I have put in quite a bit of effort searching for solutions. The problem arises when making a call from a ...

What are the steps to start using the Intersection Observer API right away?

Utilizing the Intersection Observer API, I can accurately determine whether an element is within the viewport or not. Is there a way to utilize the Intersection Observer API to detect if an element is in the viewport without relying on a callback function ...

What could be causing my Vue component to not refresh?

Can anyone help me figure out why this component isn't re-rendering after changing the value? I'm attempting to create a dynamic filter similar to Amazon using only checkboxes. Here are the 4 components I have: App.vue, test-filter.vue, filtersIn ...