1

I'm making a chrome extension which changes the background image of a new tab. The first time I load the extension the background image doesn't change.

This problem also very occasionally arises after using it for long periods of time (but I'm not sure at what times it doesn't work except on first install). Thanks.

main.js

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

   // INCLUDE JQUERY LIBRARY: OTHERWISE THIS WON'T WORK...
   // SURE YOU CAN ALSO DO ALL THESE IN PURE JAVASCRIPT, BUT WHY RE-INVENT THE WHEEL? :-)

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

               //HANDLE THE SUCCESS CASE FOR THE AJAX CALL
               success: function (data, textStatus, jqXHR) {
                   if(data){
                       localStorage.numberOfImages = data;
                       gotNumberOfImages = true;

                   }
               },

               //HANDLE THE FAILURE CASE FOR THE AJAX CALL
               error: function (jqXHR, textStatus, errorThrown) {
                   console.log('The following error occurred: ' + textStatus, errorThrown);
               },

               //HANDLE THE EVENT-COMPLETE CASE FOR 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;
   };



// Set up the image files to be used.
var theImages = new Array() // do not change this
// To add more image files, continue with the
// pattern below, adding to the array.


var numberOfImages;
if (navigator.onLine) { //checking if connected to internet, if it finds the user is online it'll call the images that are on the server.
  for(i = 0; i<=localStorage.numberOfImages;i++){
    theImages[i] = 'http://url.com/images/'+ i +'.jpg'; //NAME THE IMAGES ON THE SERVER 0.JPG, 1.JPG, 2.JPG and so on.
  }
} else { //if offline, if it finds that the user is offline it'll use these images. REMEMBER TO PUT A FEW OF THESE.
  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 name",
  "description": "Add 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>
Ron
  • 105
  • 2
  • 2
  • 10

1 Answers1

0

If the window is already loaded when you load the extension, it won't work because showNewImage() is triggered by window.onload in line 1.

add showNewImage(); a second time to the end of your script like this:

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

This will run the script when the extension is first loaded.

grateful
  • 1,128
  • 13
  • 25
  • nope, still not showing. What else can I do? Thanks for your help. – Ron May 24 '16 at 08:16
  • Perhaps, by including "persistent":false in your manifest (which creates an event page - see https://developer.chrome.com/extensions/event_pages), the script is not running continuously in the background as you wish. Try "persistent":true? – grateful May 24 '16 at 08:24
  • I've tried it. Still when I load the package it doesn't show an image the first time. – Ron May 24 '16 at 08:34
  • 1
    The background script is utterly useless, `persistent` or not, since it only contains a copy jQuery that no other script can use. – Xan May 24 '16 at 08:40
  • 1
    @Xan - you're right. @Ron - one last stab - The anonymous function to load pictures includes `$(document).ready(function(e) {`, so if the document is already ready when the extension is loaded, it won't be fired. Try removing `$(document).ready(function(e) {` – grateful May 24 '16 at 08:45
  • @grateful still doesn't load the image the **first** time I install/load it. Any other suggestions? Also, do you see any other occurrences where this error may arise? – Ron May 24 '16 at 16:53
  • Have you tried both the first suggestion "add showNewImage(); a second time to the end of your script" and the third "Try removing $(document).ready(function(e) {" together? – grateful May 24 '16 at 22:11
  • @Xan do you have a solution? – Ron May 25 '16 at 16:52
  • I suppose I do in a manner of speaking. Your AJAX request happens asynchronously, so by the time you try to use `localStorage.numberOfImages` it's not set yet. You should read the question I linked and adapt the logic accordingly - not do anything until the AJAX request succeeds or fails. – Xan May 25 '16 at 16:56
  • @Xan Thanks so much. I completely understand your answer/solution but I'm still not being able to implement it in my code. Could you please help? I've tried everything I could think of. – Ron May 25 '16 at 18:37