Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension onload behaviour

I am developing a settings page for a chrome extension. In my options.js file I want to initalize the settings with some default values and I use window.onload = initSettings(); for that. In my initSettings() function I am trying to access an input from the DOM via document.getElementById("someId"). But this call always returns null. I thought that the window.onload event is fired after all of the DOM elements are in place.

What am I doing wrong?

like image 465
cristian.petroaca Avatar asked Oct 07 '12 15:10

cristian.petroaca


People also ask

Is onload necessary?

Yes, there could be unexpected consequences. But, no, it's not absolutely necessary. The timing could be off for things still loading, like complicated layouts, deep DOM structures, dynamic HTML from other scripts, or images. To avoid these situations, it's always safest to wrap your script in an onload event.

What is onload method?

Definition and Usage The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

Is there an onload function in Javascript?

The onload in javascript is compatible with loading elements like CSS files, images, script files, etc. within a web page. The onload events are one of the most used and primarily part of the <body> tag. Another advantage is the ability of the onload event to deal with web cookies.

What is the difference between content script and background script?

Background Script - Provides persistence and handles background events. Content Script - Scripts that run in isolation in the context of the web page. Injected Script - Scripts that are programmatically injected into the web page.


1 Answers

I have this in the top of my options.js file - It's been so long since I last played with extensions, I can't be sure it's of any help. Worth a shot..

// fires when script is first loaded
// can't do onInit directly here, because the DOM hasn't been loaded for options.html yet
// we just set an event listener for document.DOMContentLoaded - In that handler we can call onInit
document.addEventListener('DOMContentLoaded', onInit, false);
like image 191
enhzflep Avatar answered Sep 20 '22 17:09

enhzflep