Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded.

This problem has also occurred very occasionally after prolonged usage (although I am unsure of specific times when it fails to work aside from the initial installation). Thank you for any assistance.

main.js

    /*THIS CODE IS FOR GETTING THE NUMBER OF IMAGES FROM PHP*/

   // INCLUDING JQUERY LIBRARY: NECESSARY FOR SUCCESSFUL FUNCTIONALITY...
   // IT'S POSSIBLE TO IMPLEMENT ALL THIS WITH PURE JAVASCRIPT, BUT WHY REINVENT THE WHEEL? :-)

   (function ($) {
       $(document).ready(function(e) {
           $.ajax({
               url: 'http://url.com/numberOfImages.php',     // <== ALTER URL
               dataType: "HTML",
               cache: false,
               type: "POST",

               //SUPPORTING A SUCCESSFUL AJAX CALL
               success: function (data, textStatus, jqXHR) {
                   if(data){
                       localStorage.numberOfImages = data;
                       gotNumberOfImages = true;

                   }
               },

               //RESOLVING AN ERROR IN THE AJAX CALL
               error: function (jqXHR, textStatus, errorThrown) {
                   console.log('The following error occurred: ' + textStatus, errorThrown);
               },

               //HANDLING THE COMPLETION OF THE AJAX CALL
               complete: function (jqXHR, textStatus) {
               }
           });
       });
   })(jQuery);






   window.onload = function() {
     showNewImage();
     var str = document.getElementById("greet").innerHTML;
     var res = str.replace("\'\'", " " + localStorage.name); // replace with name
     document.getElementById("greet").innerHTML = res;
   };



// Defining the image files to utilize.
var theImages = new Array() // refrain from altering this
// To incorporate additional image files, follow the example below and continue adding to the array.


var numberOfImages;
if (navigator.onLine) { //verifying internet connection, using images from server if user is online.
  for(i = 0; i<=localStorage.numberOfImages;i++){
    theImages[i] = 'http://url.com/images/'+ i +'.jpg'; //NAMING SERVER IMAGES 0.JPG, 1.JPG, 2.JPG AND SO FORTH.
  }
} else { //when offline, defaulting to these local images. BE SURE TO ADD SEVERAL VARIANTS.
  theImages[0] = 'image3.jpg'
  theImages[1] = 'image4.jpg'
}





var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
   preBuffer[i] = new Image()
   preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showNewImage(){
document.body.style['background-image'] = 'url("' + theImages[whichImage] + '")';
//localStorage.img = theImages[whichImage];
}

manifest.json

{
  "name": "App title",
  "description": "Include description",
  "version": "1.0",
  "permissions": [
    "activeTab"
  ],
  "chrome_url_overrides" : {
    "newtab": "main.html"
  },
  "background": {
    "scripts": ["jquery-2.2.3.min.js"],
    "persistent": false
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/",
    "storage",
    "tabs",
    "http://*/*",
    "https://*/*"
  ],
  "browser_action": {
    "default_title": "some title"
  },
  "manifest_version": 2
}

main.html

<html>
  <head>
    <title>New Tab</title>
    <link rel="stylesheet" href="main.css">
      <link rel="stylesheet" href="/octicons/octicons.css">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script src="jquery-2.2.3.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
  </head>
  <body>
...
    <script src = "main.js"></script>
  </body>
</html>

Answer №1

In case the window has already loaded before the extension is loaded, it may not function correctly as showNewImage() relies on window.onload in line 1.

To resolve this issue, simply include an additional call to showNewImage(); at the end of your script like so:

    document.body.style['background-image'] = 'url("' + theImages[whichImage] + '")';
    //localStorage.img = theImages[whichImage];
    }
    showNewImage();

By adding this extra call, the script will be executed when the extension is initially loaded.

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 we incorporate the radix-ui/colors variables into a CSS module file?

For my personal project, I am incorporating Radix components alongside radix-ui/colors. However, when attempting to import color variables into the CSS Module, I encountered an error. It seems that using the :root selector in the _app file is necessary, as ...

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...

What is the process for making an ajax call in CakePHP?

It may seem obvious, but I've searched the internet and couldn't find any useful or updated information on this topic. I'm attempting to make an ajax request in CakePHP controller to retrieve both view contents and JavaScript code. The aja ...

There was an error loading the resource as the Object does not have the method 'adGallery'

For the past two days, I have been attempting to implement the jQuery plugin "ad-gallery" on my website without success. I must mention that my knowledge in JavaScript and CSS is limited, so the issue could be something simple. The peculiar thing is that ...

Is there a way to submit an object to the server without using ajax during form submission?

I have a web application built on the ASP.NET MVC 5 framework. One of the pages in my application utilizes the amazing jQuery-QueryBuilder plugin, allowing users to create filters to refine the dataset results. When a user submits the form by clicking the ...

What are the possibilities of utilizing a variable that is stated within composition to enable dynamic rendering?

I'm working on a Vue.js v3 project using the composition API. I have defined a variable in my setup like this: setup() { const showInvoiceItemForm = true; return { showInvoiceItemForm }; }, Now, I want to show a form when a button is click ...

Running a Python script through a Javascript event

I'm looking to enhance my webpage by implementing a feature where users can generate a personalized QR code with the click of a button. My current setup involves a Python script that creates the QR code image and saves it as a .png file. I want to int ...

jQuery show/hide functionality allows you to toggle the visibility of elements

I am looking to create a toggle button that expands the menu-wrapper width and hides the sidebar when clicked. Here is the initial CSS styling: #my-wrapper { Width:500px; } #sidebar-wrapper { width:200px; } Upon clicking the button, the CSS will update ...

Ensure that only one checkbox is checked at a time and that unchecking one does not remove the

I am facing an issue with two checkboxes in my code. When I click on the first checkbox in the featured playlist section, another popular genre checkbox should be unchecked. However, only the value changes and the checked mark remains unchanged. Can anyone ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

Unable to dynamically load a component into page.tsx within Next.js

When importing a component into another component there are no issues, but when trying to import a component into a page it results in an error... I am new to this so any help is greatly appreciated. This is how I am importing: const CodeSampleModal = dy ...

Foundation Unveil Modal hidden from view

I'm currently integrating modals using Foundation 5 in a Rails application. The issue I'm facing is that the modal only works when the page is not scrolled down. If you scroll to the bottom of the page and try to activate the modal by clicking ...

Simple way to automatically reload your script using an npm server

Testing out a sample javascript code snippet. Locating a script named simple.js in the demos directory. Executing the demo using the command yarn build-demos && http-server demos/ The script simple.js is compiled to simple_bundle.js and the serv ...

Show a Pop-Up When a Key is Pressed

My website popup features a 'Close' button in the top right corner, a text section with a background image, and a 'Print' button at the bottom. The popup automatically appears when the page loads. However, once closed, there is currentl ...

Endless loop JSON vulnerability

I recently came across a discussion on Stack Overflow about Google's practice of prepending while(1); to their JSON responses. Can anyone provide guidance on what type of PHP script would be suitable for this situation? I attempted the following: $ ...

Is there a way to create a mobile-exclusive slideshow using JavaScript?

I am trying to create a slideshow on my website, but whenever I add JavaScript it seems to break the desktop version. I want these three pictures to remain static and only start sliding when viewed on a mobile device. I have searched for resources on how t ...

Inconsistencies with AJAX performance

Hey there, I'm a newbie and absolutely loving this site! Currently diving into the world of JavaScript and have been through numerous tutorials. However, I seem to be struggling with getting Ajax to work. Recently stumbled upon this code snippet on ...

Create a single line of content for a carousel display

Seeking a solution where I can have a container that slides sideways without stacking in rows, I have exhaustively searched for answers using different keywords like single row, inline, flexbox, and grid but to no avail. Any assistance will be highly appre ...

Adjustable width columns in Flexbox design

I need assistance with creating a responsive three-column grid layout using Flex in CSS. I have achieved a fairly responsive design by following the CSS provided in the fiddle link below. However, I am facing an issue where the second column (the blue one) ...

Retrieving a boolean value from a function that includes an asynchronous AJAX request

In my calendar application, I am working with an array of dates: <div v-for="date in dates">{{ date }}</div> I want to apply a conditional class based on the outcome of an isWeekend() method that involves making an API call: <div v-for="d ...