Utilizing the Chrome Extension API: Accessing chrome.tabs.captureVisibleTab from Background Page to Content Script

My main objective was to capture a screenshot through the background page using:

http://developer.chrome.com/extensions/tabs.html#method-captureVisibleTab

and then transmit it to the content script for further analysis and customization utilizing the page's HTML DOM.

However, I encountered difficulty in passing the dataUrl back to the content script via Message Passing :

http://developer.chrome.com/extensions/messaging.html

I attempted JSON.stringify() without success.

The code below is functioning perfectly:

background.js

chrome.runtime.onMessage.addListener(
    function(request,sender,sendResponse){
        sendResponse({imgSrc:'hello'});
    });

But when I switch to the following code, nothing seems to work:

background.js

chrome.runtime.onMessage.addListener(
    function(request,sender,sendResponse){
        chrome.tabs.captureVisibleTab(
            null,
            {},
            function(dataUrl) {
                sendResponse({imgSrc:dataUrl});
            }
        )}
);

The only evidence that the background page has successfully captured a screenshot is if I execute:

chrome.tabs.captureVisibleTab(null,{},function(dataUrl){console.log(dataUrl);});

and I witness

"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAA....etc..."

printed in background.html, confirming its validity

My query is: How can I transfer this URL to the content script?

I would rather not conduct all the processing on the background page which lacks control over the actual visible page.

Answer №1

Implement chrome.tabs.sendMessage and be sure to include return true

background script:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        chrome.tabs.captureVisibleTab(
            null,
            {},
            function(dataUrl)
            {
                sendResponse({imgSrc:dataUrl});
            }
        );

        return true;
    }
);

content script

chrome.runtime.sendMessage({msg: "capture"}, function(response) {
  console.log(response.dataUrl);
});

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

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Creating React Views - A guide to rendering manually

https://github.com/reactjs/express-react-views I'm interested in utilizing a similar tool to render html content, but I'm not looking to integrate it with an express server. Instead, I have a node code that generates html files periodically. Wha ...

Enrollment of Vue components

After importing the component into the JavaScript file, I added it to the index.vue file as follows: import fmsSubUnitDetails from '../subunitDetails'; export default{ components: { fmsSubUnitDetails }, } Despite this, I am still encount ...

Deciphering JSON data into specialized subclasses

{ "Class1": { "Class2": [ {"Name": "DerivedV1"}, {"Name": "DerivedV2"}, {"Name": "DerivedV3"} ] } } JsonConvert.DeserializeObject<Class1>(jsonString, settings); public class Class1 { p ...

Fixing the slide bar in React using styled components

In the early stages of creating a slider where cards (divs) can be moved left and right with a click, I encountered an issue. The onClick handler is functioning properly. However, upon running the project, I noticed that the cards start 230px away from the ...

Including a fresh JSON entity into an array within a file

I am working with a JSON file that contains an array of objects under "NavigationControls". My goal is to add a new item to this array and update the file. I would appreciate any tips or guidance on how to achieve this. Thank you! { "LocalId": "sect ...

The setTimeout functionality is executing faster than expected

In my selenium test, I've noticed that the setTimeout function consistently finishes about 25% faster than it should. For example, when waiting for 20 seconds, the function completes after only 15 seconds. test.describe('basic login test',f ...

What is the best way to run an external JavaScript file at regular intervals?

I enjoy loading an external JavaScript file every 10 seconds, or whenever the page body is clicked (in which case, the script should only run if a few seconds have passed). If you could provide me with some documentation on this topic, that would be grea ...

Setting the number of search results displayed per page on Algolia autocomplete can be done by

According to the documentation on autocomplete, it mentions the following about hits: Hits To create a source based on Algolia's hits array, simply use: { source: autocomplete.sources.hits(indexObj, { hitsPerPage: 2 }), templates: { sugge ...

Trying to bring in components from directories above

I'm currently facing an issue with importing components from a parent directory into my project. My goal is to be able to use these components across multiple projects, which seems like the most straightforward approach. However, when I attempt this, ...

Jackson's @JsonView is not functioning properly as per expectations

Currently, I am working with Jackson JSON 1.9.12 in conjunction with SpringMVC. As part of this, I have created a data transfer object (dto) with JSON fields. To have two profiles of the same dto with different JSON fields, I took the approach of creating ...

Can grapesjs be integrated into AngularJS using a controller?

JavaScript Question var app = angular.module('CompanyProfile', []); app.controller('CompanyProfileCtrl', function() { function initializeEditor() { var editor = grapesjs.init({ allowScripts: 1, ...

Unable to locate additional elements following javascript append utilizing Chrome WebDriver

I have a simple HTML code generated from a C# dotnet core ASP application. I am working on a webdriver test to count the number of input boxes inside the colorList div. Initially, the count is two which is correct, but when I click the button labeled "+", ...

Avoid having individual words centered on a single line of text

Currently, I'm in the process of developing a website using WooCommerce, WordPress, and Elementor. I've encountered an issue where only one word appears on each line and have tried various solutions such as hyphens, word-break, and line-break wit ...

Error: The request was denied by the operating system. Issue encountered while attempting to build a new React application

I recently installed the LTS version 14.17.3 of Node (npm version 6.14.13). Following that, I successfully globally installed create-react-app using the command "npm install -g create-react-app" (version 4.0.3). However, when attempting to create a new R ...

Fastify endpoint failing to respond to designated URL

Within my code, there is a router setup: fastify.get('/:link', (req, reply) => { req.params.url = req.host+req.url; reply.view("template.ejs",req.params); }); I am trying to capture URLs and process them in the template. All URLs are ...

Content changing programmatically does not reset the scrollHeight

As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the ...

Using Ansible's RAW module for leveraging Curl commands and JSON files in a Kubernetes environment

How can I use curl to parse a JSON attribute named keys_base64 in Ansible's raw module due to a network issue? Despite trying various approaches, I am still unable to get it to work. Update: Solution Found Original Post ** Example of JSON Keys Obje ...

HTML5 input type Color displays individual RGB values

This code snippet opens up a variety of options for the user to manipulate different color values such as R, G, B, HEX VALUE, HUE, etc. However, the specific requirement is to only extract the Red value. <input id="color_pick"type="color" value="#ff0 ...

Determine the quantity of items within a JSON array

There is a json array located at the following url: http://localhost/heart/api/restApiController/dataset.json The structure of the json array is as follows: [ { Weight: "3", Smoking: "1", Exercising: "0", Food_habits: ...