Cannot retrieve Global variables when using chrome.tabs.executescript in Chrome 55

After recently updating Chrome to version 55.0.2883.75, I encountered an issue with my self-developed Chrome Plugin used for parsing HTML files. In the plugin, I utilize chrome.tabs.executescript to retrieve data from a background HTML page. Previously, I successfully saved the parsed data from the background page into a global variable using chrome.extension.onRequest and accessed it in the callback function of chrome.tabs.executescript for processing.

However, upon upgrading to Version 55.0.2883.75, this functionality stopped working. How can I now access the global variables in the new version?

Below is a snippet of my code:

Step 1 :

chrome.extension.onRequest.addListener(
    function (request, sender, sendResponse) {
        parser = new DOMParser();
        htmlDoc = parser.parseFromString(request.content, "text/html");

        // The outputJson global variable is populated here
        outputJson = parseMyPage(outputJson, htmlDoc);
    });

Step 2:

chrome.tabs.getSelected(null, function (tab) {
    // Inject script onto the page
    chrome.tabs.executeScript(tab.id,{
        code: "chrome.extension.sendRequest({content: document.body.innerHTML}, function(response) { console.log('success'); });"
    }, function () {

       // Code to access global variables
if (outputJson && null != outputJson) {
    // Perform other actions based on the global variable
}

    });
}); 

Answer №1

Your code relies on the order in which two asynchronous blocks of code are executed: the extension.onRequest1 event and the callback for tabs.executeScript(). However, there is no guarantee that these will happen in the required sequence. This could lead to issues on users' machines, especially depending on their configurations. It's possible that older versions of Chrome handled this differently.

To address this issue, consider redesigning your code so that it does not depend on a specific order of execution for asynchronous code blocks. This can help simplify your code as well.

An effective solution is to transfer the desired information from the content script directly to the background script within the callback of the tabs.executeScript(). By passing the value of the executed script to the callback, you can efficiently share data between the content script and the tabs.executeScript() callback. Keep in mind that only one value per frame can be sent back this way.

The modified code snippet below achieves what you need. I have manually edited this code based on yours and another answer here:

chrome.tabs.getSelected(null, function (tab) {
    // Inject a script onto the page
    chrome.tabs.executeScript(tab.id,{
        code: "document.body.innerHTML;"
    }, function (results) {
        parser = new DOMParser();
        htmlDoc = parser.parseFromString(results[0], "text/html");
        // Populate the global variable outputJson here
        outputJson = parseMyPage(outputJson, htmlDoc);
        
        // Accessing global variables
        if (outputJson && null != outputJson) {
            // Other operations
        }
    });
}); 

  1. extension.sendRequest() and extension.onRequest are deprecated since Chrome 33. Consider using runtime.sendmessage() and runtime.onMessage instead.

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

No information retrieved from Ajax request

I've been utilizing the following jQuery code to execute an ajax call: $.ajax({ url: "/projects/project/xGetProjectStatus", type: "GET", dataType: "json"}) .done( function(request){ alert(request.responseText); ...

What is the best way to divide an array while extracting data from a JSON object using

Currently, I am parsing the json data. My goal is to find a specific property within the json object that contains two nested arrays (list and array). However, when extracting the values, they are all being stored in a single array. Is there a way to separ ...

Having trouble with submitting data in an ExpressJS POST request while using mongoose?

As I embark on building my first express.js application, I encounter my initial obstacle. The setup is rather simple. Routes in app.js: app.get('/', routes.index); app.get('/users', user.list); app.get('/products', product. ...

`res.render when all data queries are completed``

When I make an app.get request in my server.js file, I retrieve a dataset from MongoDB and then render my page while passing the data to it. Here is an example: //page load app.get('/', (req, res) => { //find all data in test table ...

Tips for uploading a file using Axios in a form

When uploading a file to a Flask server, I can access files from the flask request global by using raw HTML with the following code: <form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data> < ...

Built-in functionality in aws-amplify for seamless redirection to Microsoft sign-in page within a ReactJS application

Important Note: I prefer not to use the built-in hostedUI page of AWS Cognito service. I have a customized login page where I have already integrated Google and Facebook login options by adding two additional buttons labeled Google Login and Facebook Logi ...

Accessing data in JSON format from a URL

I'm working on a website that analyzes data from the game Overwatch. There's this link () that, when visited, displays text in JSON format. Is there a way to use JavaScript to read this data and display it nicely within a <p> tag on my si ...

Error encountered when attempting to have multiple chrome.runtime.onMessage listeners - port disconnection issue

I am currently developing a chrome-extension that utilizes the Dexie indexedDB Wrapper, various jQuery Libraries, and syncfusion's eGrid to manage and display data. While I know this issue has been addressed multiple times in the past, I have encounte ...

What is the proper way to designate a manifest.json link tag on a limited-access website controlled by Apache shibboleth?

The issue arises when attempting to access the manifest.json file. It has been declared as follows: <link href="manifest.json" rel="manifest"/> Is it possible to declare the manifest tag inline, or what would be the most effective way to declare it ...

incorporating numerous interconnected javascript files within a single html document

I have a pair of JavaScript files (file1, file2). File1 utilizes a class that is defined in file2. Can I include these files in an HTML document like this: <script type="text/javascript" src="file1.js"></script> <script type="text/javascrip ...

What is the process for importing Buffer into a Quasar app that is using Vite as the build tool

I'm having issues with integrating the eth-crypto module into my Quasar app that utilizes Vite. The errors I'm encountering are related to the absence of the Buffer object, which is expected since it's typically found in the front end. Is ...

Error encountered: Unexpected token while trying to implement React + Node.js tutorial on a blog platform

I recently started following a tutorial on Site Point in an attempt to create my own React app. However, I hit a roadblock at these specific steps: mkdir public npm install npm run developement The first command failed for me because I already had a &a ...

Combining platform-express and platform-fastify for optimal performance

I am currently working on a NestJS application and my goal is to upload files using the package @types/multer. However, I encountered an issue while following the guidelines from the official documentation: https://i.sstatic.net/JCX1B.png Upon starting ...

What is the process for enabling HLS.js to retrieve data from the server side?

I have successfully implemented a video player using hls.js, and I have some ts files stored in https:/// along with an m3u8 file. To read the content of the m3u8 file, I used PHP to fetch it and sent the data to JavaScript (res["manifest"] = the content ...

Verify whether a web application is equipped with React, Angular, or Vue

Is there an easy way to identify the client-side libraries used by an application if they are minified or compressed? While examining all the JavaScript sent from the server to the client, it can be challenging to determine if one of the top three popular ...

Is it possible to integrate a collection of libraries along with external dependencies into Vite?

Currently, I am in the process of packaging a library for npm that uses type: "module". To accomplish this, I have configured vite's library mode with the following settings: export default defineConfig({ css: { postcss: { plugin ...

What is the best way to send a custom property through Vue router?

I'm currently working with a route instance: const router = new Router({ routes: [ { path: '/', name: 'Home', component: MainContainer, redirect: '/news/list', children: [ { ...

What is the best way to establish my permit requirements on a monthly basis?

An employee is only allowed to request up to 3 permits per month. If they need a fourth permit, they will have to wait until the following month. Here is my table structure for permissions: Permissions id (integer), format (text), date_r ...

Creating a blank webpage after including a component tag for an Angular form

I encountered an issue while developing an Angular form. It seems that using the app-name-editor tag causes my entire HTML page to go blank, and the form does not display. However, removing the tag restores the webpage's functionality. This leads me t ...

Using Vue Js directive to implement a Select2 component

I've been exploring the example of the Vue.js wrapper component and trying to customize it to use a v-select2 directive on a standard select box, rather than creating templates or components for each one. You can view my implementation in this JS Bin ...