What is the best way to transfer a content script variable to a background script in a Chrome Extension?

I am looking to transfer a variable named "website_hostname" from the content script to the background script. This variable holds the hostname of the website you are currently visiting.

Content Script:

var website_hostname =  window.location.href;

//Code for sending website_hostname 

Background Script:

// Retrieve website_hostname 

Answer №1

To achieve this, you can utilize the chrome onMessage function.

Within the content of your script:

//content-script.js

function notifyExtension() {
  chrome.runtime.sendMessage({"url": window.loaction.href});
}
//background.js
chrome.runtime.onMessage.addListener(notify);

function notify(message) {
     variable = message.url
  });
}

This helpful information was sourced from https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage

Answer №2

In a similar vein to the suggestion made in the previous response, it would be beneficial to utilize long-lived connections ports for this task.

For more information on long-lived connections, please visit this link.

To establish a connection, use the following code: var port = chrome.runtime.connect() Send a message to the background page using port.postMessage()

Listening for responses:

To listen for responses, use the following code: for response, port.onMessage.addListener()

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

"Error: The functionality of finding places on Google Maps is not

I've encountered an issue while trying to integrate Google Maps into my Node application. The map is loading correctly and I'm able to retrieve my location. However, I am facing a problem with implementing the Google Places API code to allow user ...

JavaScript Linked List Operations: Issues with the removeHead() and contains() Functions

Incorporating ES6 syntax, the challenge is to construct a linked list and subject it to an npm linter test. Below is the code implementation: class LinkedList { constructor() { this.head = null; this.tail = null; // Do not alter anything wit ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

Angular Controller is not able to retrieve the Route Parameter, resulting in a 404

Currently working on my very first web app using Node.js and AngularJs. I've encountered a roadblock with the following code: var app = angular.module('Martin', ['ngResource','ngRoute']); app.config(['$routeProvide ...

After successfully uploading a file, refresh the file list using AngularJS, DropzoneJS, and JSON

In my "file manager page," I am using DropzoneJS for uploading files and AngularJS ng-repeat to display all the saved files. The file list is retrieved through an ng-controller that uses an http.get request to fetch a JSON file with the file list. When Dr ...

Sending a parameter to a form within Edge Animate

I'm facing an issue where I need to pass a variable to a form from Edge Animate. Here's the current instruction snippet: sym.$("form").append('<iframe width="100%" height="100%" src="login_PRA.php?v_id="vidn frameborder="0" scrolling="no ...

Guide on reusing javascript to toggle between image sources

I have a simple website with buttons that, when clicked, change the image being displayed. However, I find myself repeating code for each button, and I'm wondering if there is a more efficient solution to this problem. Here is an example of what I cu ...

Please explain this ES6 syntax to me: Using a colon after a function call

While exploring the documentation for a flux store in React, I came across an example that caught my attention. import {ReduceStore} from 'flux/utils'; class CounterStore extends ReduceStore<number> { getInitialState(): number { ret ...

What is the best way to prevent double clicks when using an external onClick function and an internal Link simultaneously

Encountering an issue with nextjs 13, let me explain the situation: Within a card component, there is an external div containing an internal link to navigate to a single product page. Using onClick on the external div enables it to gain focus (necessary f ...

Refresh TR when clicked

I have a HTML table that lists items from SQL, using <tr> and <td>. The table is housed within a div that is refreshed every 30 seconds with jQuery AJAX (hence the unique id on the div). Here is the HTML code: function auto_load() { $.aj ...

Having trouble with React Testing Library throwing an error every time I try to use fireEvent on an input text?

When attempting to utilize the "fireEvent" method from React Testing Library, I encountered an error as shown below: MainSection.test.js: test('Verifying SearchBar functionality', async () => { render(<SearchBar />); const text ...

Retrieve the object filtered by a specific group from an array of data

I have a data object that contains various groups and rules within each group item. My task is to filter the rules based on a search query, while also displaying the group name associated with the filtered rule. { "id": "rulesCompany", "group": [ ...

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

What is the correct way to invoke a function contained within an object that is stored in an array?

I've encountered a problem with my program. I'm attempting to invoke a function that is part of an object stored in an array, but I'm having difficulty calling the function correctly. //Initialize Array for Storing Projects let allProjects ...

Tips for effectively utilizing MeteorPad: (Note: ensure to use at home instead of at work due to potential firewall or proxy issues)

UPDATE: It's possible that the issue is related to a firewall or proxy. MeteorPad doesn't work at my workplace, but it works fine at home. I've been attempting to use MeteorPad () but I'm encountering some difficulties. The bottom are ...

Inquiry on integrating Spotify with Axios for my debut solo project (beginner inquiry)

I have a question regarding my first solo project in React. I started learning code in September and I'm facing an issue while making a POST request to the Spotify API to retrieve an access token: Despite following the recommended 'Content-Type& ...

What is the best way to retrieve the specific property from a bound function?

I'm looking to retrieve the value of a specific property from a function that has already been bound. function foo(){ console.log(this.a) } const bar = foo.bind({a:1}) bar() // Outputs 1 bar.getThis() // expected result is { a: 1 } Given the code ...

Disabling an image is similar to deactivating a button

document.getElementById("buttonName").disabled = true; I have successfully disabled a button using the code above. However, I am now facing a challenge with using pictures as buttons that have an onClick function. Is there a way to disable the onClick fun ...

Type parameter in express.js route

If I have this specific route in my Express.js server: router.get('/ad/:id', (req, res) => { const { id } = req.params Ad.getAd(id, (err, resp) => { if(err){ return handleError('Failed to load an ad' ...

Unable to retrieve information from JSON file utilizing AngularJS version 1.6

I'm having trouble retrieving data from my JSON file using AngularJs 1.6 myApp.controller("homeCtrl", function($scope, $http) { $scope.Data = []; var getJsonData = function() { $http.get('contactlist.json').then(func ...