Extension: Facilitating communication to a newly opened window through chrome.windows.create

I am currently facing a challenge in determining the most effective way to communicate with my web application, which is being opened using chrome.windows.create within my extension.

Despite successfully establishing the connection between the content script and background script, I am encountering difficulties when attempting to utilize the value received from the background script in my web application. Specifically, the value needs to be loaded into an editor within the web app.

I have experimented with assigning functions and variables to the window and tab objects, but these seem to disappear once the web app is loaded. Additionally, using chrome.tabs.executeScript allows me to manipulate the DOM but prevents me from setting global variables on the 'window' object.

If no superior method exists, I may have to resort to adding elements to the DOM and retrieving them once the web app has loaded. However, this approach seems less than ideal. Ideally, I would prefer a cleaner solution, such as implementing an onLoadFromExtension function that my web app can execute to obtain the necessary value.

Answer №1

After numerous attempts and experiments, I finally discovered a method that works, although it still appears to be prone to errors. It's worth noting that the success of this method relies on ensuring the extension ID matches the installed one. If this cannot be hardcoded, it may require passing through an additional channel. However, upon further research, it seems that hardcoding is possible as the extension ID is a hash of the public key – problem solved! This experience has led me to consider that perhaps manipulating the DOM could offer a cleaner solution...

background.js:

var selectedContent = null;
chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    console.info("------------------------------- Got request", request);
    if (request.getSelectedContent) {
      sendResponse(selectedContent);        
    }
  });

web app:

var extensionId = "naonkagfcedpnnhdhjahadkghagenjnc";
  chrome.runtime.sendMessage(extensionId, {getSelectedContent: "true"},
    response => {
      console.info("----------------- Got response", response);
      if(response) {
        this.text = response;
      }
    });

manifest.json:

"externally_connectable": {
  "ids": ["naonkagfcedpnnhdhjahadkghagenjnc"],
  "matches": ["http://localhost:1338/*"]
},

Answer №2

  1. Here are the steps to follow within the popup window:
    const parentWindow = window.opener
    parentWindow.postMessage({ action: 'opened' })
    window.onmessage = msg => {
      alert(JSON.stringify(msg.data)) // A message will pop up showing {"your":"data"}
    }
    
  2. In the script that triggers chrome.windows.create, include the following:
    window.onmessage = msg => {
      if (msg.data.action == 'opened') {
        msg.source.postMessage({ your: 'data' })
      }
    }
    
  3. Remember to use setSelfAsOpener: true when utilizing chrome.windows.create

How does this process function?

With the Chrome extension, the windows API has certain limitations. For communication between the created window and its creator (window.opener), a message needs to be sent from the new window or else the creator won't have access to a WindowProxy (which is helpful for sending messages to the new window).

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

What's the best way to showcase data in a column dynamically depending on its specific columns?

I have an array of objects representing columns and another array representing table data. I need to dynamically display the data in the specified columns. Some objects have 3 key-values which should be displayed in specific columns. The second object in ...

Locking state object and properties as read-only in ReactJS/Typescript

I have an object from a third-party class and I want to ensure that its properties are read-only. This means that I do not want to be able to change the state with this.state.object.props = "xx"; The structure of the object is as follows: class ThirdPart ...

Tips for sending event and additional arguments to a click handler

Hi there, I recently created a canvas using easelJS. Within my canvas, I have points that have a click handler defined for them with this syntax: p.on("click", handleMouseClickEvent); However, I am facing an issue when trying to pass arguments to the han ...

What is causing the sorting table to fail in React when using useState?

import React, { useState } from "react"; import "./App.css"; const App = () => { const [data, setData] = useState([ { rank: 1, name: "John", age: 29, job: "Web developer", }, { rank: 2, name: "Micha ...

Error occurred in imagemin: [TypeError: (input, output, options) => {

function optimizeImages(originalFilePath, destinationFilePath) { return new Promise(function (resolve, reject){ var Imagemin = require('imagemin'); console.log(originalFilePath); // /app/public/images/temporary/4du_QIGCJb5.jpeg con ...

Creating a collection of arrays that are named based on the properties of an object

After calling an ajax service, I received a collection of objects where Object (A) properties are Group, order, salary. For example, the objects could be [Employee, 1, 1500],[Management, 2, 2000], [Employee, 3, salary]. My task is to create an array for e ...

Show a collection of titles for unique post types

I am currently showcasing a custom list of post types using the following code: <!-- Displaying post type list --> <?php $args = array( 'post_type'=>'artworks_post', 'title_li'=> __(&apo ...

Issues with the parseInt() Function

I'm having trouble figuring out why parseInt() isn't working correctly in my code, especially when passing numbers through to my function parameters. It keeps returning NaN in both my array and the function's return value. What I'm att ...

Ensure the appropriate TypeScript types are utilized for error middleware in Express

Struggling to properly define the types in my express application. I am encountering issues with my middleware error function and cannot seem to find a suitable example or get the correct types set up. Despite numerous attempts, here is my current version: ...

Access the contents of an array nested within an object in JavaScript without the need for a traditional for loop

My code is functioning properly: var roles = user.getRoles() for (var i = 0; i < roles.length; i++){ if (Roles[i].getName()== ‘Admin’){ --this line is reached } } Nevertheless, I am contemplating if there's a way to achieve ...

What is the best way to deliver static HTML files in Nest.js?

I am encountering an issue with loading JS files from a static /dist folder located outside of my Nest project. While the index.html file loads successfully, any JS file results in a 404 error. In another Node/Express.js project, I am able to serve these ...

ng-include once the application has finished loading

Currently, my server is using handlebars to generate the initial HTML page. I would like to include a ng-include in this page to dynamically update the client side. However, every time my application runs, it loads the page and the data-ng-include="templa ...

Issues arising when using December in a JavaScript function to determine weekends

My function is used to determine if a day falls on the weekend or not, and it works perfectly for most months except December. What could be causing this issue? weekEnd: function(date) { // Determine if it's a weekend var date1 = new Dat ...

Can properties be modified in a nested child component within vue.js without requiring a sequence of events throughout the entire hierarchy?

In various instances, it has been advised against mutating properties in vue.js, as it is considered an anti-pattern. Even mutating object properties or using functions like this.$set to add elements to an object that is given as a property is discouraged. ...

Error: Unable to access the 'searchField' property because it is null

An error occurred: Cannot find the searchField property of null in App.render https://i.sstatic.net/ZYp3L.png ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

Is it possible to configure Webpack/NextJs to handle a recurring import path mapping?

Exploring ways to streamline imports in my NextJs Project (v14.1.3), I'm interested in finding a method to modify the import statement below: import foo from 'path/to/foo/foo' To possibly simplify it to: import foo from 'path/to/foo&ap ...

ng-bind-html behaving unexpectedly

index.html <div ng-bind-html="htmlElement()"></div> app.js $scope.htmlElement = function(){ var html = '<input type="text" ng-model="myModel" />'; return $sce.trustAsHtml(html); } However, when attempting to retrieve t ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...