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

Can you explain the role of the %GetOptimizationStatus function within a JavaScript file executing in Node.js?

Currently, I am delving into an article that discusses optimization strategies and includes the following code snippet: //Function that contains the pattern to be inspected (using an `eval` statement) function exampleFunction() { return 3; eval(&a ...

A quick guide on automatically populating text boxes with characteristics of the item chosen from a drop-down menu

On my webpage, I am looking to automatically populate textboxes with information (such as common name, location, etc.) of the selected shop from a dropdown list without having to refresh the page. Here is the dropdown list: <select id="shops" class="f ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Passing variables from ExpressJS to JavaScript can be a seamless process

I am struggling with this issue; I am utilizing NodeJS to retrieve a JSON and I must transfer the variable to my page for use by JavaScript. app.get('/test', function(req, res) { res.render('testPage', { myVar: 'My Dat ...

In order to manage this specific file type, you may require a suitable loader. React in conjunction with Material UI could be the

I recently created a project using Material UI and React JS, but I encountered a puzzling error without making any changes to my app. Despite reaching out for help by creating an issue on MUI, I received no response. The app was generated using npx-create ...

Recognizing when a Bootstrap dropdown with multiple options is deselected through Jquery

I'm working with a dynamic bootstrap multiple drop-down selector and I need to execute some code when a user deselects an option. <select id="selectOptions" multiple> <option>Test1</option> <option>Test2</option> & ...

Encountering a Problem with Image Rendering in Next.js

Issue: I am facing a problem while trying to display a react component using <Gallery images={images} />. The component itself is rendered, but the images from the array are not showing up initially. However, when I resize the screen by dragging the ...

Ways to insert user data into a hidden input field

I am facing an issue with the input field on my website. Users can enter their desired input, and this data is copied into a hidden input field. However, the problem arises when new data replaces the old data. This is where I copy all the data: $('# ...

Highlight react-bootstrap NavItems with a underline on scroll in React

I am currently working on a website where I have implemented a react-bootstrap navbar with several Nav items. My goal is to enable smooth scrolling through the page, where each section corresponds to an underlined NavItem in the navbar or when clicked, aut ...

Prevent a form from loading depending on the response received from an ajax callback

I am currently working on implementing an ajax post function. The process involves sending data and receiving a callback from PHP with some data in return. Depending on the returned data, I need to make a decision whether to proceed or allow the user to re ...

Checking to see if all the users mentioned in the message have been assigned a role

Hello everyone, I'm new to asking questions here so please bear with me. I am trying to retrieve all the users mentioned in a message and check if any of them have a specific role, such as the staff role. Thank you for your help! Edit: Here is the ...

Is there a way to disable the animation on the MaterialUI Switch component?

Hi there, I am a beginner in React and currently working on developing a Chrome extension using it. One of the challenges I am facing is with the Switch component from MaterialUI that I am using inside my popup page. To manage its state, I am currently st ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

Modification of a CSS element

The CSS I am working with looks like this: .cls .imageX { float:left; } .cls .imageY { float:right; } It is currently being used on a page in this way: <div class="cls"> <a href="" class="imageX"><img src="left.png"/></a> &l ...

Incorporate the variable into the JSON string using Json in C#

I'm encountering an issue while trying to include my string username and password in the jsonData string. public async Task<string> authLogin(string username, string password) { var client = new HttpClient(); client.BaseAdd ...

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 ...

How can I customize the visibility toggles for the password input field in Angular Material?

Currently immersed in the Angular 15 migration process... Today, I encountered an issue with a password input that displays two eyes the first time something is entered in the field. The HTML code for this is as follows: <mat-form-field appearance=&qu ...

Encountering an error when attempting to upload a file to S3 using JS Vue

I'm attempting to upload a file to my S3 bucket using the aws-s3 library, but I am encountering this error in the console: https://i.stack.imgur.com/lk47U.png Here is the code for the component: <template> <input type="file" @ch ...

The incorrect sequence of Angular/Protractor functions is causing issues within the tests

Trying to extract the values from a column in a grid and compare them before and after sorting can be tricky. I have two functions set up for this task - one to retrieve the initial column values, and another to check the order post-sorting. However, there ...