Transferring information from a webpage to a popup using executeScript: A guide

I've successfully retrieved data from a website, but I'm struggling to send it to popup.js. I attempted to use executeScript with a callback, but it's not working for me.

popup.js

function getData() {
    chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
        chrome.tabs.executeScript(tabs[0].id,{
            file: 'getdata.js'
        });
    });
}
document.getElementById('clickme').addEventListener('click', getData);

 function loadData() {
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
              chrome.tabs.update(tabs[0].id, {url: tabs[0].url});
                chrome.tabs.executeScript(tabs[0].id,{
                    file: 'loaddata.js'
              });
             });
          }

document.getElementById('clickme2').addEventListener('click', loadData);

getdata.js

var div = document.querySelectorAll('div');
var array = [];
div.forEach(function(item) {
    item.getAttribute('data');
    array.push(item.getAttribute('data'));
});
console.log(array);

loaddata.js

var div = document.querySelectorAll('div');
div.forEach(function(item, i){
    item.setAttribute('data', array[i]);
});

manifest.json

{
    "manifest_version": 2,
    "name": "aa",
    "description": "bb",
    "version": "1.0",
    "icons": {
        "48": "icon.png"
    },
    "permissions": ["tabs", "<all_urls>", "contentSettings", "contextMenus", "unlimitedStorage"],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
            "js": ["jquery-3.2.1.min.js", "popup.js"]
        }
    }
}

EDIT: 1. I successfully retrieved data using executeScript after adding array at the end of getdata.js.

  1. How can I send an array from popup.js/getdata.js to loaddata.js?

Answer №1

In the official documentation, it is stated that:

"The script's result is the last statement evaluated"

Thus, it is recommended to modify your getdata.js file by adding a single line at the end instead of using console.log(array) within the executeScript callback:

array;

This change will help you achieve the desired outcome.

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

End all occurrences of XMLHttpRequest

In my code, I am calling the function SigWebRefresh at specific intervals of 50 milliseconds. tmr = setInterval(SigWebRefresh, 50); The function SigWebRefresh utilizes XMLHTTPRequest: function SigWebRefresh(){ xhr2 = new XMLHttpRequest(); ...

I possess 9 captivating visuals that gracefully unveil their larger counterparts upon being clicked. Curiously, this enchanting feature seems to encounter a perplexing issue within the realm of web browsing

<style type="text/javascript" src="jquery-1.11.0.min.js"></style> <style type="text/javascript" src="myCode.js"></style> </body> //jquery is within my site directory on my desktop $(document).ready(function(){ //note: $("#ar ...

Azure Chatbot that logs conversations in Webchat whenever the user selects 'none of the above' option

Recently, I've delved into the world of web chat services and embarked on a journey to craft a chat bot using pure JavaScript code that can seamlessly integrate into any HTML file. Despite consulting Microsoft's documentation, I find myself in a ...

Issue: The THREE.GLTFLoader cannot process this asset. Only glTF versions below 2.0 are compatible

Upon utilizing three.js, I encountered an error while parsing data from the GLTF JSON file. This file was exported from the three.js 3D viewer and editor, indicating a version of 4.5 in the JSON content. Highlighted below is the JSX code snippet: import { ...

Issue with drawing the sub menu (Sidr) not being displayed

I've implemented the Sidr Menu plugin on my Wordpress site. However, there are some issues with Sidr's mobile layout that I was able to fix using a bit of JavaScript. <script type="text/javascript"> jQuery( window ).load(function() { ...

Injecting variables into HSL color values within Three.JS

In my current code, I have set 2 HSL colors: scene.background = new THREE.Color("hsl(0, 100%, 50%)"); var light = new THREE.AmbientLight("hsl(180, 100%, 50%)"); I am attempting to pass a variable for 'hue' from my CSS. After ...

How can I fix the issue of the onClick function in my React list not activating the toggle?

How to Activate Toggle Functionality Currently, I am working on a project using React where I developed a list with active states. I have implemented the onClick functions, but unfortunately, they are not working as intended. When I click on the list item ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

Instructions for utilizing a non-string reference without triggering flow errors

I've noticed that string refs are considered legacy in React. You can read more about it here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md However, I am encountering a flow error in my component and I&apo ...

Modifying the dimensions of media:thumbnail in Blogger's RSS Feed

I came across this post, but it seems like there have been updates in the past 4 years regarding how thumbnails are generated for Blogger posts. I've attempted various methods, but so far none of them have been successful. If anyone could assist me in ...

Trigger a 'change password' notification using Javascript

Issue: I am currently working on developing a web application that includes a password change functionality without the use of form submission. The process I have in mind is as follows: Show a Bootstrap modal pop-up User enters new password Upon clickin ...

N8N: Deleting JSON Key from Output

Is it possible to remove the json key in my output file? I am unsure of the best approach to achieve this. I would like to return an array of data with all values, not just one value. If you want more information, here is a link to my N8N post: Manipulate ...

The "begin" parameter of the Angular limitTo filter appears to be ineffective in Angular version 1.3

Currently, I am attempting to implement a pagination feature on an array of users using Angularjs 1.3. ng-repeat="user in users | filter: searchText | orderBy: 'lastName' | limitTo:pageSize:startPosition track by user.lanId" I specifically want ...

CSS rotation causing issues with absolute positioning

In the example below, I have demonstrated the current behavior I am experiencing and the desired outcome. // Rotated div rotated.style.left = "50px"; rotated.style.top = "100px"; // Original "untouched" div original.style.left = "50px"; original.style.t ...

How can I trigger an event to append a UL element using

Can anyone suggest a more elegant solution for handling an append/remove event from an element without having to manually trigger an event or resorting to other methods? It would be great if there was a way to do something like this: $('#id').o ...

Three.js displaying only a fraction of gltf model on screen

I've been experimenting with adding this gltf model () using threeJS. The current code snippet is the only approach that has shown me a glimpse of the object, albeit just a small part. If anyone has insights on what modifications are needed, any assis ...

Ways to avoid losing data when a page is refreshed

After encountering a frustrating issue with my form, I turned to research in hopes of finding a solution. However, each attempt has resulted in disappointment as the data is lost every time the page is refreshed. If anyone has advice on how to prevent th ...

JavaScript makes it possible to access subnodes in XML by utilizing specific methods and

I am looking to utilize javascript to extract data from an XML file that has been loaded into a webpage. Below is the XML file (a.xml) that I am working with. a.xml <?xml version="1.0"?> <Step rID="T6"> <Obj ><![CDATA[Get Data Ta ...

Unexpected issue with PHP/Ajax/JQuery response functionality

I am experiencing an issue with my index.php file. Here is the code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="ajax.js"></script ...

What is the best way to design a dynamic menu using HTML, CSS, and jQuery, where each li element gradually disappears?

Consider this menu structure: <ul class="main-menu"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> </ul> My task is to dynamically hide th ...