Interconnection between a particular webpage and a Chrome browser extension

I am attempting to establish a communication channel between a specific webpage (for example: www.website.dev) and a Chrome extension that I have created.

While using postMessage allows me to communicate from the webpage to the extension, I am experiencing difficulty doing so from the extension to the webpage.

I have tried Google's example, but it utilizes a background page which complicates things for me.

Thank you for your assistance

EDIT: I apologize, but I am confused about the distinction between content_script and background.js. In my manifest file, I have specified a content script called test.js. What role does "background" play in this context?

Answer №1

By referring to the official documentation, it is possible to send messages to your extension by utilizing the extension ID:

Configuration in manifest.json file:

"externally_accessible": {
  "domains": ["*://*.example.net/*"]
}

On the website side:

// The specific ID of the target extension.
var extensionID = "123xyz456abc789def123xyz";

// Send a simple request:
chrome.runtime.sendMessage(extensionID, {openUrlInEditor: url},
  function(response) {
    if (!response.success)
      handleError(url);
  });

Inside the extension:

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    if (sender.url == blocklistedWebsite)
      return; // deny access for this webpage
    if (request.openUrlInEditor)
      openUrl(request.openUrlInEditor);
  });

Answer №2

To access all the necessary information, refer to the documentation https://developer.chrome.com/extensions/messaging

The communication process involves one part using the sendMessage function while the other part listens for the event, which can be a webpage or content script.

Either the content script of the webpage should start the communication (providing the tab id) or you can have the background query tabs with specific URLs and then use sendMessage. Note that there are two distinct functions used here: chrome.extension.sendMessage and chrome.tabs.sendMessage.

The code below has been tested by me and works effectively:

content_script.js:

chrome.extension.sendMessage({"msg":"hello"});

background.js:

chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.msg == "hello"){
    senderTab = sender.tab.id;
    chrome.tabs.sendMessage(senderTab, {"msg": "ehlo"});
  };
})

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

Stop GIFs from playing automatically

Looking for a solution to disable autoplay for animated gifs on my chat-site (php-based). Tried script below but out of ideas: <script> myVid=document.getElementsByTagName('img'); function disableAutoplay() { myVid.autoplay=false; m ...

Node: How can I retrieve the value of a JSON key that contains a filename with a dot in

I have a JSON file named myjson.json, with the following structure: { "main.css": "main-4zgjrhtr.css", "main.js": "main-76gfhdgsj.js" "normalkey" : "somevalue" } The purpose is to link revision builds to their original filenames. Now I need to acce ...

Convert HTML templates into JavaScript on the client side using Angular framework along with Browserify, Babel, ES2015, and Gulp

Having trouble with my Browserify Angular configuration file, specifically when using require() to load HTML templates. I attempted to use stringify or browserify-ng-html2js in the transform() function, but it resulted in multiple transform calls in my gul ...

ways to retrieve information from a JavaScript array in jade

I am currently working with the twitter-js-client and vis timeline libraries to create a timeline feature. In my index.js file, I parse a JSON object containing tweets using JSON.parse() and then pass this data to a Jade template to be displayed on the tim ...

Leveraging Multiple MongoDB Databases in Meteor.js

Can 2 Meteor.Collections fetch data from separate MongoDB database servers? Dogs = Meteor.Collection('dogs') // mongodb://192.168.1.123:27017/dogs Cats = Meteor.Collection('cats') // mongodb://192.168.1.124:27017/cats ...

The jScrollPane fails to remain at the bottom

I have implemented jScrollPane for the scrollbars in a chat interface that I created. However, I am facing an issue where the scroll does not automatically go to the bottom as expected. I have set the 'stickToBottom' option to true and also enabl ...

What is the best way to locate this particular element on the webpage?

After using the right-click and selecting inspect element, I located the code of the desired element on the webpage: <input type="text" ng-if="!editing" ng-model="item.Price" ng-click="inputFocus()" ts="" required="" placeholder="قیمت :" class="ng- ...

Discover the method to retrieve the month name from an HTML Date input value

Here we have a date input field <input id="customer-date" name="customer-date" type="date" required> Accompanied by this script const customerDate = document.getElementById('customer-date').value; const dateHandler = document.getElementB ...

Creating an animated scrolling image effect: A step-by-step guide

My current project involves implementing a scrolling textbox. I have put together the following snippet to achieve this: <html> <head> <style type="text/css"> #scroll { position: absolute; white-space: nowrap; ...

Using Jquery to Modify Information within HTML Table Cells

My dilemma involves an HTML table where each cell will have two data attributes. My goal is to create a button that toggles the value displayed in the table between these two attributes. <table class="table1"> <tbody> <tr> <td data-or ...

When utilizing ExpressJS, you can easily implement the app.use method with the specified route. By calling router.get and providing the route as "/", you

Having trouble with a part of my code. When trying to access localhost:3000/, I'm not getting a response. Using Express 4.7.4 and the latest node version on Ubuntu Trusty. app.js ///// Dependencies & config var express = require('express&a ...

Ensuring the slide toggle's status with Cypress validation

As a beginner in Cypress, I am looking to ensure that I can accurately determine the status of the slide toggle button - whether it is ON or OFF. The code below helps to check for this condition but I am unsure about how to implement it within an If-Else s ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...

Is there a different alternative to @JavascriptInterface in Android WebView?

I understand how to invoke a Java method within JavaScript code using the @JavascriptInterface annotation. However, I am facing an issue when trying to determine which JS method should be called from Android. Currently, I am triggering an Android Dialog ...

The unexpected occurence of the Onbeforeunload exception

I am attempting to create an exception for onbeforeunload and display a warning about potential data loss whenever the quantity is not zero: Here is what I have tried so far: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...

How can we identify if a React component is stateless/functional?

Two types of components exist in my React project: functional/stateless and those inherited from React.Component: const Component1 = () => (<span>Hello</span>) class Component2 extends React.Component { render() { return (<span> ...

Reload the precise URL using JavaScript or jQuery

I need a solution to refresh the current URL after an ajax success. I attempted the following methods: location.reload() history.go(0) location.href = location.href location.href = location.pathname location.replace(location.pathname) However, I encounter ...

Problem with Angular2, NodeJS, and Passport Integration

At the moment, my Angular2 front-end is running on localhost:3000 while the NodeJS back-end (using KrakenJS) is running on localhost:8000. When I input the credentials and make a call to the this.http.post('http://localhost:8000/login', body, { h ...

Hexadecimal characters are randomly injected into the source code of websites

On specific computers, strange hex codes are appearing randomly in the source code of our web pages across all tested browsers (Chrome, Safari, IE, and Firefox). They seem to occur approximately every 8000 characters with a new line before and after. Here& ...

Optimizing your approach to testing deferred always

When creating test cases for code within a jQuery AJAX call's always method or in bluebird promises' finally function, it often involves the following structure: function doStuff() { console.log('stuff done'); } function someFunct ...