The communication between the extension and chrome.runtime.connect() fails, possibly due to an issue with the chrome manifest version

I've been working on converting a Chrome extension that stopped functioning in manifest version 2. I've removed inline JavaScript and switched from chrome.extension.connect to chrome.runtime.connect. However, I'm still encountering issues with chrome.runtime.connect (which I changed from chrome.extension.connect). Any suggestions?

File ContentScript.js

OnDocumentEnd();

var TranslitOn;
var ToggleKeyCode;
var LocalEnabled;
var port;

var ChangeListener = function (event) { OnChange(event); };

var KeyUpListener = function (event) { OnKeyUp(event, event.target); };
var KeyDownListener = function (event) { OnKeyDown(event); };
var KeyPressListener = function (event) { OnKeyPress(event, event.target); };


function OnDocumentEnd() {
    console.log("ode");

    port = chrome.runtime.connect();

    port.onMessage.addListener(function (msg) {
    console.log("port on msg");
        if (msg.Status != null) {
    console.log("1:"+msg.Status);
   //        TranslitOn = msg.Status;
        }
        if (msg.ToggleKey != null) {
    console.log("2:"+msg.ToggleKey);
           ToggleKeyCode = msg.ToggleKey;
        }
        if (msg.IsEnabled != null) {
    console.log("3:"+msg.IsEnabled);
           LocalEnabled = msg.IsEnabled;
            if (LocalEnabled) {
                Bootstrap();
            }
        }
    });
    port.postMessage({ GetEnabled: true });
    }

File translit.js

<script language="JavaScript" type="text/javascript" src="/import/jquery-2.0.3.min.js"></script>
<script language="JavaScript" type="text/javascript" src="/import/sha1Hash.js"></script>
<script language="JavaScript" type="text/javascript" src="/import/ArrayList.js"></script>
  <script type="text/javascript">


    if (localStorage.getItem('t_hotkey') == null) {
        localStorage.setItem('t_hotkey', 113);
    }

    var ToggleKeyCode = localStorage.getItem('t_hotkey');


    var TranslitOn = false;

    var GlobalEnabled = true;
    var Ports = new ArrayList();

    function FireOnEvent() {
        try {
            chrome.tabs.getSelected(null, function (tab) {
                chrome.tabs.sendRequest(tab.id, { SetStatus: TranslitOn });
                chrome.tabs.sendRequest(tab.id, { ToggleKey: ToggleKeyCode });
            });
        } catch (e) { }
    }

    function Toggle() {
        TranslitOn = !TranslitOn;
        FireOnEvent();
    }

    function UpdateToggleKey() {
        FireOnEvent();
    }

    function Save() {
        try {
            localStorage["ToggleKey"] = ToggleKeyCode;
            localStorage["Enabled"] = GlobalEnabled;
        }
        catch (e) { }
    }

function Init() {
    try {
        chrome.runtime.onConnect.addListener(function (port) {
          port.onMessage.addListener(function (msg) {
            if (msg.GetStatus != null) {
              port.postMessage({ Status: TranslitOn });
            }
            else if (msg.GetToggleKey != null) {
              port.postMessage({ ToggleKey: ToggleKeyCode });
            }
            else if (msg.GetEnabled != null) {
              port.postMessage({ IsEnabled: GlobalEnabled });
            }
          });

          Ports.Add(port);
        });

        chrome.browserAction.onClicked.addListener(function (tab) { Toggle();});

        chrome.runtime.onRequest.addListener(function (request, sender, sendResponse) {
          try {

            if (request.SetStatus != null) {
              if (request.SetStatus != TranslitOn) {
            Toggle();
              }
            }

            if (request.ToggleStatus != null) {
              Toggle();
            }

            if (request.SetToggleKey != null) {
              ToggleKeyCode = request.SetToggleKey;
              UpdateToggleKey();
            }

            if (request.SetEnabled != null) {
              GlobalEnabled = request.SetEnabled;
            }

          }
          catch (e) { }
        });
    } catch (e) { }
}

File manifest.json

{
   "background": {
   "scripts":["translit.js"],
   "persistent": false},
   "content_scripts": [ {
      "all_frames": true,
      "js": [ "/import/jquery-2.0.3.min.js", "/code/ContentScript.js" ],
      "matches": [ "http://*/*", "https://*/*" ],
      "run_at": "document_end"
   } ],
   "description": "xxxxxxxxxxt",
   "icons": {
      "128": "img/Icon128.png",
      "32": "img/Icon32.png",
      "48": "img/Icon48.png"
   },
   "key": "MIIBIjAxxxxxxxxB",
   "manifest_version": 2,
   "name": "xxxxxxxxxxxxx",
   "permissions": [ "storage", "tabs", "http://*/*", "https://*/*" ],
   "short_name": "xxx",
   "update_url": "http://clients2.google.com/service/update2/crx",
   "version": "1.23"

}

Answer №1

To successfully integrate translit.js, it is important to eliminate any remaining HTML code at the beginning. Instead, ensure that all necessary links to JavaScript files are added to the background scripts js array within the manifest file. By following this process, your implementation should function seamlessly:)

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

Tips for effectively utilizing vue-draggable (or Sortable JS) within a v-data-table using the powerful combination of Vuetify 2 and Vue JS 2

I'm currently experimenting with integrating vue-draggable into Vuetify's v-data-table based on the instructions provided in this article : https://medium.com/vuetify/drag-n-drop-in-vuetify-part-ii-2b07b4b27684 The article mentions : "The main o ...

I'm feeling completely lost trying to understand cors in conjunction with fetch, particularly when an options request is

I am using whatwg fetch in the code snippet below: const headers = new Headers(); //uncommenting this causes the preflight options request to be sent //headers.append('x-something', 'foo'); const response = await fetch(&apos ...

Using the shift() method in Javascript to manipulate Objects

My goal is to take my list and combine the first two items (0 & 1) together. I attempted the following code: total=foo.shift(); foo[0]=total However, I encountered this error: Uncaught TypeError: Object [object Array] has no method &ap ...

Using the useState Hook: What is the best way to add a new item to the end of an array stored in the state

I'm currently working on a project using Next.js and Tailwind, where I am trying to populate an array using the useState Hook. My intention is to iterate through the array using the map function and add items to the end of the array until there are n ...

When attempting an ifelse combination, only a singular object of length 1 will be returned

Running this code will provide information about financial statements. library(RJSONIO) data<-fromJSON("http://www.registeruz.sk/cruz-public/api/uctovny-vykaz?id=4455316",encoding = "UTF-8") Executing the following code will generate a vector of lengt ...

The MediaSource API is not supported on Chrome 27

My current browser version is Chrome 27, and based on this source, it is indicated that the MediaSource API comes pre-installed. However, upon further examination on the same page, the test section states that Your browser does not support the MediaSource ...

Adding map markers from a JSON feed to your React Google Map - a step-by-step guide!

I'm currently working on a React project that involves integrating Google Maps: const MarkerComponent = ({text}) => <div>{text}</div>; export default class NavMap extends Component { constructor(props) { super(props); this.s ...

Manage how data is presented in a JSON format using Go's structures

Currently, I am working on a nested structure in golang and trying to manage which substructures should be displayed in JSON. For example, if I only want to show the treeid and name fields from Citrus, I attempted the following notation, but it still prin ...

Eliminate redundant XML entries when using jQuery autocomplete

Does anyone know how to prevent duplicate records from appearing in a jQuery autocomplete dropdown? I am pulling data from an XML file and want to ensure that each record is unique and only displayed once. You can see the issue here ...

Obtain JSON data from an array

I am currently using the Slim framework to create a REST API. In my code, the route for tasks is defined as follows: $app->get('/tasks', 'authenticate', function() { global $user_id; $response = array(); $items = array() ...

A guide on sending arguments to a react function component from a JSX component via onClick event handling

Below is a brief excerpt from my extensive code: import React from "react"; const Home = () => { return ( imgFilter.map((imgs) => { return ( < Col sm = "3" xs = "12" key ...

Avoiding the utilization of automatically generated JSON files as a data source in Rails when

I have implemented javascript code that uses JSON to generate a timeline. The JSON is being created using json_builder and it contains only the current user's information. The JSON displays correctly when accessed directly through its URL, but when th ...

Notification Click Event for PWA Service Worker

I am attempting to display a notification and trigger an action when it is clicked. try { navigator.serviceWorker.getRegistration() .then(reg => { reg.showNotification("Check out the video clip!", { body: "Cl ...

Is there a way to display the inbox area upon completion of the document loading process?

I'm currently working on creating an inbox feature for my personal portfolio, mostly as a learning exercise rather than for any practical use. However, I've run into an issue where all emails are being displayed by default when the page loads wit ...

Exploring different ways to make API requests using technologies like jQuery, Angular, and more

I'm new to APIs and I want to create an eco game with Facebook for London and Amsterdam. To do this, I need to obtain data from APIs in each city. After doing some research, I think I can request information on the client side of the app, process it, ...

What is the best way to monitor changes in objects within a JavaScript array?

Currently, I am in the process of developing a Todo application using electron and Vue.js. In my project, there is an array of objects called items. Each object follows this format: {id: <Number>, item: <String>, complete: <Boolean>, ...

What is the proper way to retrieve the value of the key "order" from this JSON object (containing semicolons in the name)?

Vijay Anand inquired about this particular matter yesterday, unfortunately, the discussion was closed before receiving any solutions: HTTP Response: { "entry": { "@xml:base": "https://API_PROC_SRV/", "@xmlns": "http://www.w3.org/2005/Atom", ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Error: You can't call .text as a function in jQuery

While trying to retrieve the text from my td, I encountered the following error: $tds[2].text is not a function. The output of console.log('td',$tds[2]) shows: https://i.stack.imgur.com/OUngP.png $(document).ready(function() { $trs = $(&ap ...

Ways to conceal a div using jQuery when the video source is missing

If there is no source in the video, I want to hide the video_wrapper class <div class="video_wrapper" style="width: 100%; height: 100%; display: none;"> <video id="df-video" playsinline="" webkit-playsinline="" style="height: 100%; width: 100%; ...