The information was not displayed in the message exchange

I'm currently working on a project involving a google chrome extension where the content.js script sends a message to popup.js. I'm also attempting to take some text from content.js and display it in popup.js. Here is my entire code:

Here's my manifest file, manifest.json:

{
    "name": "Hoko's Extension",
    "description": "My Extension",
    "version": "1.0",
    "manifest_version": 3,
    "action": {
        "default_popup": "popup.html" 
      },
      "content_scripts": [
        {
          "matches": ["https://*/*", "http://*/*"],
          "js": ["content-script.js"]
        }
      ],
      "background":  {
        "service_worker": "background.js"
      },
      "permissions": [
        "tabs",
        "activeTab"
      ]
  
}

This is the popup displayed when you click the icon in the toolbar, popup.html:

<html>
    <head>
        <title>Title</title>
        
    </head>
    <body>
        <h1>This is the Popup</h1>


<p id="extensionpopupcontent"></p>
<script type="text/javascript" src="popup.js"></script>
    </body>
</html>

Below is my content script named content-script.js:

function injectScript(file_path, tag) {
    var node = document.getElementsByTagName(tag)[0];
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', file_path);
    node.appendChild(script);
}

injectScript(chrome.runtime.getURL('inject.js'), 'body');


chrome.runtime.sendMessage(document.getElementsByTagName('title')[0].innerText);

In background.js, I am receiving messages from content-script.js.

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
  function onMessage(request, sender, sendResponse) {
    console.log(sender.tab ?
    "from a content script:" + sender.tab.url :
    "from the extension");
    if (request.greeting == "hello") {
       sendResponse({farewell: "goodbye"});
    }
}
})

In popup.js, I receive messages from background.js and output the code from content-script.js.

window.addEventListener('DOMContentLoaded', () => {
let bg = chrome.extension.getBackgroundPage();


    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
            document.getElementById('extensionpopupcontent').innerHTML = response;
         });
    

});

});

I believe I need to include this script inject.js:

function click() {
    return document.getElementsByTagName('title')[0].innerText;
}

click();

Answer №1

  1. delete background and content_scripts from manifest.json file
  2. exclude tabs permission from the manifest.json
  3. eliminate background.js, content-script.js, and inject.js files
  4. revamp popup.js as shown below:
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
  document.getElementById('extensionpopupcontent').textContent = tabs[0]?.title;
});

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

Transform the Vue.js component into a Webpack component

I found this code in a tutorial and now I need to make some modifications so it can be compiled with Webpack, including the template script and CSS files. <html> <head> <title>VueJs Instance</title> <s ...

Help needed with PHP, MYSQL, and AJAX! Trying to figure out how to update a form dynamically without triggering a page refresh. Can anyone

Hey there! I'm fairly new to the world of dynamically updating databases without needing a page refresh. My goal is to build something similar to The end result I'm aiming for includes: Dynamically generating fields (Done) Loading existing dat ...

A guide to troubleshooting the "Cannot resolve all parameters error" in Angular

Recently delved into the world of angular 2, and I've come across my first challenge. I'm trying to establish a service for retrieving data from a server but I keep encountering this particular error Error: Can't resolve all parameters fo ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

Is there a way to connect either of two distinct values in Angular?

Looking to assign the data with two possible values, depending on its existence. For instance, if I have a collection of TVs and I want to save the "name" value of myTVs[0] and myTVs[1]. For example: var myTVs = [ { "JapaneseTV": { ...

Display images in a list with a gradual fade effect as they load in Vue.js

In my Vue project, I am looking to display images one at a time with a fading effect. I have added a transition group with a fade in effect and a function that adds each image with a small delay. However, I am facing an issue where all the images show up ...

Exploring, navigating, and cycling through JSON in Node.js

I'm currently attempting to extract the titles of front page articles from Reddit's RSS feed and running into some issues. Below is the snippet of code I am working with: //var util = require('util'); //var cheerio = require('chee ...

Design interactive Vue form with customized questions based on user response

I am looking to dynamically create a form with conditional fields. The structure of the form is stored in an object called Q. Below is an example of a Vue component that utilizes bootstrap-vue. <template> <div> <div v-for="q of ...

Retrieve the value with `eventArgs.get_value()` function to obtain the selected text instead of the ID

When I populate a textbox with autocomplete using the code below, it only returns the selected text and not the rowid. Any idea why alert(eventArgs.get_value()) doesn't return the actual ID of the row in SQL? <script language="javascript" type="te ...

What is the reason behind the length property belonging to an array object?

While there are other instances, let's focus on the length property for now. Why does it appear as if we're copying it here: [].hasOwnProperty("length") //==> true It is common knowledge that an array's length property belongs ...

Navigating within two containers using the anchorScroll feature in AngularJS

I am trying to create a page with two columns of fixed height. The content in each column is generated using ng-repeat directive. Is it possible to implement scrolling within each column to a specific id using AngularJS? Code <div> Scroll to a p ...

Displaying live data from a spreadsheet directly on a sidebar

My goal is to extract data from another sheet in the same spreadsheet and present it as a dropdown selection in the sidebar. The code.gs file contains a function called getVisualData() that successfully retrieves the desired list: function getVisualData() ...

The extensive magnetic scrolling functionality in Ionic 2 sets it apart from other frameworks

Hi everyone, I could really use some assistance! I've been working on developing an Ionic 2 App and my navigation setup is not too complex. I have a main menu where clicking on an item opens another menu with a submenu. From there, if I click on an i ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

Converting Dynamo DB stream data into Json format

I need to convert the DDB stream message into a standard JSON format. To achieve this, I am using unmarshalleddata = aws.DynamoDB.Converter.unmarshall(result.NewImage); where result.NewImage is { carrier: { S: 'SPRING' }, partnerTransacti ...

What is the process for inserting text or letters into a checkbox using Material Ui?

I am looking to create circular check boxes with text inside them similar to the image provided. Any help or guidance on achieving this would be greatly appreciated. View the image here ...

Parsing JSON into a List of Objects

Here is a filter string in the following format: {"groupOp":"AND","rules":[{"field":"FName","op":"bw","data":"te"}]} I am looking to deserialize this into a Generic list of items. Any tips on how I can accomplish this? ...

Verify the existence of the email address, and if it is valid, redirect the user to the dashboard page

Here is the code snippet from my dashboard's page.jsx 'use client' import { useSession } from 'next-auth/react' import { redirect } from 'next/navigation' import { getUserByEmail } from '@/utils/user' export d ...

Trouble resolving a timer interruption in JavaScript

Creating dynamic elements using PHP has brought me to a new challenge. I want to implement a functionality where the user can hover over an icon and see the related element, which should disappear after some time if the mouse leaves the icon. Additionally, ...

What methods can I use to prevent repeated login requests to SalesForce databases when using Express.js routers?

Is there a way to avoid logging into SalesForce databases and passing queries on multiple routers in express.js? It's tedious to login every time. If you have any suggestions, please let me know. var conn = new jsforce.Connection({ oauth2 : salesfo ...