Is there a way to transfer an image from background.js to background.html?

I'm in the process of creating a chrome extension that involves making an API call every hour to retrieve an image, which I then want to save in chrome.storage.local.

However, the size of the image is quite large, so I'm resizing it using a canvas.

My approach involves injecting the source URL (obtained from the API call) into an image tag within my background.html file.

Here is an excerpt from my manifest:


{
"manifest_version": 2,
  "name": "moodflow",
  "short_name": "moodflow",
  "description": "",
  "version": "0.0.0.10",
  "author": "Walter J. Monecke",
  "chrome_url_overrides" : {
    "newtab": "index.html"
  },
  "background": {
    "scripts": ["./js/jquery-3.2.1.min.js", "hot-reload.js", "background.js"],
    "pages": ["background.html"]
  },
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "permissions": [
    "storage",
    "alarms",
    "unlimitedStorage",
    "activeTab",
    "https://www.youtube.com/iframe_api",
    "https://api.unsplash.com/photos/random",
    "https://api.unsplash.com/photos/random/*"
  ]
}

Below is the jQuery AJAX code snippet from my background.js:

$.ajax({
    url: "https://api.unsplash.com/photos/random",
    type: 'get',
    async: true,
    dataType: "json",
    data: "client_id=29b43b6caaf7bde2a85ef2cfddfeaf1c1e920133c058394a7f8dad675b99921b&collections=281002",
    success: (response) => {
        alert('successful API');
        alert(response);
        // insert src into img 
        $('#source_img').css('display', 'none');

        $('#source_img').on('load', function() {
            alert('Image has loaded!');
            //compressImageAndSave();
        }).attr('src', response.urls.raw);
      },
        error: () => {
          alert('getPictureApi AJAX failed');
        }
    });

And here is my background.html code snippet:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <img src="" id="source_img">
  </body>
</html>

I suspect that my mistake lies in assuming that my background.js can directly interact with my background.html file.

What do you think I might be doing wrong?

Answer №1

It's important to note that only one background page is allowed. At this moment, you are attempting to declare two background pages: "scripts" creates an autogenerated empty page and "pages" is an invalid declaration for a normal background page.

To resolve this issue, remove the "scripts" section, include the js files using <script> tags in your html, and ensure that you use the correct "page" declaration with a single value.

manifest.json

{
"manifest_version": 2,
  "name": "moodflow",
  "short_name": "moodflow",
  "description": "",
  "version": "0.0.0.10",
  "author": "Walter J. Monecke",
  "chrome_url_overrides" : {
    "newtab": "index.html"
  },
  "background": {
    "page": "background.html"
  },
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "permissions": [
    "storage",
    "alarms",
    "unlimitedStorage",
    "activeTab",
    "https://www.youtube.com/iframe_api",
    "https://api.unsplash.com/photos/random",
    "https://api.unsplash.com/photos/random/*"
  ]
}

background.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <img src="" id="source_img">
    <script src="./js/jquery-3.2.1.min.js"></script>
    <script src="hot-reload.js"></script>
    <script src="background.js"></script>
  </body>
</html>

and keep background.js as is.

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

When utilizing an 'imported' asynchronous function, make sure to clean up the useEffect

Please do not mistake this for a duplicate. Despite my thorough search on various blogs and sources, I have yet to find a solution. My primary question is 'how can I address the error of react state change in unmounted component, and also cancel an a ...

Show the GitHub repositories of the user within a React application

Even though I am relatively new to React, I managed to create a GitHub search application. In this app, you can input a user's name in a search box and view their avatar, bio, username, etc. However, I'm facing an issue with fetching their reposi ...

What is the process for implementing a grid with 5 columns on larger screens and 2 columns on smaller screens using reactjs?

I am currently working on building a Grid using material UI and reactJs. I found the guidelines on this link https://mui.com/system/react-grid/. However, there seems to be an issue with creating 5 columns in the grid. I attempted to create a custom grid ...

Encountering a Javascript Error when trying to begin

As a beginner in Javascript, I am venturing into designing a simple website that incorporates Javascript. Currently, my focus is on building a calculator. However, upon loading my website, nothing seems to initiate and there are no error messages displayed ...

Attempting to conceal a div element along with its contents using AngularJS

I am attempting to use AngularJS to hide a div and its contents. I have defined a scope variable initialized as false and passed it to the div in order to hide it. However, the div is still visible along with its content. <script type="text/javascr ...

Utilize AngularJS to inject a service into a module without assigning it to a variable, enabling easier minification

Currently, I am attempting to decrease the size of my AngularJS JavaScript code (using SquishIt). Within my module, there is a service injected as a function argument, as shown below. var myapp = angular.module('myapp', ['ngSanitize'] ...

Instructions on transforming an img into an Image component within next.js

I have successfully implemented all the logic in this component, tailored to the <img> tag. Now, I am aiming to apply the same logic to the Image component. However, when attempting to do so, I encounter an error. TypeError: Failed to construct &apos ...

Displaying images in Dash Python by utilizing external Javascript

Dear audience, I am looking to incorporate an image on a Python Dash webpage that is created by JavaScript code. For more details, you can refer to the documentation here: . To include this script in a static HTML page, one would typically add the followi ...

Is there a way to dynamically add an option to multiple select boxes and then only redirect the browser if that specific option is chosen using jquery/js?

Presently, this is the code I am working with. The URL validator is specifically included because there was an issue with redirection occurring on any option selected, however, I only want a redirect to happen when the options I add with jQuery are clicked ...

Easiest Method to Populate a Dropdown Menu from a JavaScript Array and Change the Default Selection with AngularJS

Looking for some assistance with a Javascript Array. Here is a sample array: var directionArray = [{ id: 'N', text: 'North' }, { id: 'S', text: 'South' }, { id: 'E', text: 'East' }, { id: &ap ...

What is the process for sending values to a component?

I am working with a component called MyComponent: export class MyComponent { @Input() active:boolean; constructor() { console.log(this.active); } } In this component, I have declared an Input, and I pass it in as follows: <mycomp ...

Deregister channel listener

My application has a functionality where users can subscribe to Twilio chat channels. When a user clicks on a channel, the chat opens up, messages are loaded, and the user is subscribed to receive new messages using this.state.channel.on('messageAdded ...

Can a javascript code for "Infinite Scroll" be created to manage the back button?

Head over to this website: Experiment with the infinite scroll feature. You may notice that when you click a link and then press "back", there are some glitches. Therefore, I am considering developing my own version of an Infinite Scroll functionality. ...

How can I make my Background change on click using hexadecimal color codes?

I am struggling with changing the background color of an html document using a button click. While colors like "yellow, "blue", and "red" work perfectly, I encounter an issue when trying to use hexadecimal colors such as "#000000". The if-condition doesn ...

Utilize AngularJS ng-repeat directive to refine JSON objects

I'm working on an angular js controller with a json array that organizes countries by continents. Each continent consists of its own array of countries. //CONTROLLER app.controller('CountryController', function(){ this.continents = ...

Enhanced Search and Replace Techniques in HTML using jQuery and JavaScript

Although I have some experience with jQuery and Javascript, I am by no means an expert. I have been struggling to find a way to achieve my goal using minimal resources. Maybe you can assist me: This is what I am trying to accomplish: I would like to use ...

A JavaScript object featuring a predefined value

I have a simple goal that I'm unsure about achieving. My objective is to create an object that will return a specific value if no property is specified. For example: console.log(obj) // Should output "123" console.log(obj.x) // Should output "ABC" ...

Issue with dynamic creation of menu in React Material UI where onClose function is unable to reference a variable inside the function

As I develop an app, I have chosen to dynamically construct the settings menu based on a JSON file. { categories: [ { name: "General", index: 1, items: [{ name: "Dark Mode", index: 1 ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...

Evaluate the advancement of a test using a promise notification for $httpBackend

I am currently utilizing a file upload feature from https://github.com/danialfarid/angular-file-upload in my project. This library includes a progress method that is triggered when the xhr request receives the progress event. Here is an excerpt from the so ...