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

Display multiple series in Highcharts using JSON data, with each series having a unique style based on its

Is it possible to style different series on Highcharts based on JSON names? $.each(names, function (i, name) { $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?' ...

Res.redirect() function does not redirect the browser URL as expected when triggered by a request made through a frontend fetch() call

Encountering a new issue that is challenging me. In the backend, there is an API route that redirects the browser URL to /signin using res.redirect('/signin'). Upon this redirection, React Router triggers the rendering of a 'log back in&apos ...

Unexpected results occur when accessing data in $uibModal.open() within Angular JS causing it to

Here is the code snippet that is causing the issue of returning undefined items in AngularJS: App.js code console.log('single page application script is working'); var myApp = angular.module("demoApp", ["ngRoute", 'ui.bootstrap',&apos ...

The values returned by a NodeJS script in the Python shell are identical to those returned by Node

The following program was developed to address an issue in another application. In this program, a Python script is called from Node.js to perform a task. The Python script returns results that are then used in Node.js. NodeJS : var pythonShell = require ...

Generate fake data for all possible combinations using JSON faker

In my current project, I am in need of creating test data for a JSON schema. I came across this fantastic github resource that has been incredibly helpful: https://www.npmjs.com/package/json-schema-faker#overview Now, how can we expand it to generate all ...

Develop an interactive single-page scrolling system for seamless navigation between points

Creating a navigation that scrolls to the selected element when clicking on an <a> tag is my current project. I want it to animate smoothly during the transition. The navigation should go from: <a href="#Home">Home</a> To: <div id= ...

JavaScript button is not functioning properly to increase or decrease the value in the input field

I'm facing an issue with the javascript increase/decrease buttons on my website. When I assign my JS variable as the class name of the input field, pressing the button results in all input fields being affected simultaneously: https://i.stack.imgur.c ...

Quasar - Optimize for varied platforms

Currently, I am endeavoring to set up a project with various environments including staging, production, testing, and development. When using Vuejs, this task is quite straightforward. vue-cli-service build --mode staging Additionally, I need to create a ...

Click a button to adjust the height of an element

My webpage features a dashboard with tabs on the left and corresponding content on the right. To ensure proper alignment, I have utilized Bootstrap to create two columns - one for the tabs and one for the content. However, I am facing an issue where the bo ...

What is the best way to change a string containing single quotes to double quotes in order to JSON parse it

My PHP code involves encoding an array using json_encode. $params = array(1=>'something','2'=>'two'); While the encoding process itself works fine, I encountered an issue when trying to embed the JSON data into an anc ...

Issue with the navbar toggler not displaying the list items

When the screen is minimized, the toggle button appears. However, clicking it does not reveal the contents of the navbar on a small screen. I have tried loading jQuery before the bootstrap JS file as suggested by many, but it still doesn't work. Can s ...

There is a runtime error in Microsoft JScript, as the object does not support the property or method '__defineGetter__'

Upon opening my project in IE9, I encountered the error message: "Microsoft JScript runtime error: Object doesn't support property or method 'defineGetter'." Can anyone provide guidance on how to resolve this issue? ...

Navigate to the specified URL once the Ajax function has completed successfully

I'm having trouble with opening a URL from an Ajax function. It seems like the URL is not being called. This is the code I am using: $(document).on( "click",".btndriver", function() { var id = $(this).attr("id"); var nombre = $(this).att ...

Adjusting a NodeJS module for easier integration into codebases

I have organized some functions in a file within a node module structure... Here are the files and folder structure I created: - package.json - README.md - LICENSE.md - code |_______ code.js Currently, to use these functions, I include them like th ...

Steps for dynamically executing an Angular ng-include directive in real-time

Is there a way to dynamically insert an ng-include element into an HTML page and have it function properly? I am working on a Drag N Drop application where users can drag an element onto the page, and upon dropping it in the designated zone, the original ...

How can Selenium be used to identify an Internet Explorer browser extension?

Can Selenium be used to detect internet explorer browser plugins? For example, if I open a URL on IE and want to check for any installed plugins, is there a way to automate this with selenium? ...

The functionality of the UI Bootstrap custom directive controller does not seem to be recognized

I am trying to implement UI Bootstrap Collapse within my custom directive called <collapse> Unfortunately, I am encountering the following error: Error: [ng:areq] Argument 'CollapseDemoCtrl' is not a function, got undefined You can view m ...

Using Angular.js, apply the "visible" class conditionally based on a variable

My Cordova application is built with angular.js and consists of the following 2 files: app.html <div ng-controller="MyAppCtrl as myApp" ng-class="myApp.isWindows() ? 'windows' : ''"> and app.controller MyAppCtrl.$inject = [&ap ...

Vue: Optimizing JSON response filtering

I am struggling with filtering a JSON response using Vue. return this.offers.filter(type => type.offers == 'Junior'); When I keep it as return this.offers, the following is displayed in my HTML: {"-MN5agCddYAdy7c8GSSz": { "comp ...

A guide to using JavaScript to create a button that can dynamically change stylesheets

Just a heads up, I'm not using classes in this particular scenario. Can't seem to find the answer to this exact question. With javascript, how can I code a button to switch stylesheets every time it's clicked? I've experimented with d ...