Ronen Cypis Ronen Cypis - 9 months ago 70
Javascript Question

Chrome Extension: How to manipulate browser_action.default_popup DOM

For some reason, when i try to access the DOM of the

default_popup
on a
browser_action
, I can't... No js errors, it just seems like the script is running in a different context than i expected it to.
Here are the relevant code sections from
manifest.json
,
browser_action.html
&
browser_action.js


manifest.json:

"browser_action": {
"default_icon": "icons/icon.png",
"default_title": "title goes here",
"default_popup": "src/browser_action/browser_action.html"
},


browser_action.html:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="browser_action.js"></script>
<div id="mainPopup">
<h1 id="title">Main Title</h1>
<img src="http://placehold.it/700x350" alt="chart" id="chart" />
</div>


browser_action.js:

(function(){
var $title = $('#title');
console.log($title.length); // 0
})();

Answer Source

Wait for the DOM to prepare itself:

$(function() {
var $title = $('#title');
  console.log($title.length);

});

Alternatively, move your script file down:

<div id="mainPopup">
    <h1 id="title">Main Title</h1>
    <img src="http://placehold.it/700x350" alt="chart" id="chart" />
</div>

...
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="browser_action.js"></script>
</body>