The user is trying to change the content of a popup window created by a Google Chrome extension. They have provided JavaScript and HTML code that works as expected when run on JSFiddle, but fails when executed as a Chrome extension. The issue seems to be that the code is targeting the main Chrome window instead of the intended popup window.
The code provided by the user includes a JavaScript function mkSidebar
that generates HTML content based on the parameter passed to it. This content is then assigned to an element with the ID sidebar
using the innerHTML
property.
mkSidebar = function(which) {
var text = "" +
"<span " + ((which === "data") ? "id='selected'" : "") + ">Data</span>" +
"<span " + ((which === "logic") ? "id='selected'" : "") + ">Logic</span>" +
"<span " + ((which === "match") ? "id='selected'" : "") + ">Math</span>";
document.getElementById("sidebar").innerHTML = text;
};
The HTML code includes a body
element that calls the mkSidebar
function with the argument 'data'
when the page loads, and a div
element with the ID sidebar
that should be populated with the generated content.
<body onload="mkSidebar('data');">
<div id='sidebar'></div>
</body>
The user suspects that the issue is caused by the code trying to find the sidebar
element within the main Chrome window, instead of targeting the popup window created by the extension. This suspicion is confirmed when they manually run the mkSidebar('data');
command in the popup window's console.
The solution provided by one of the answers is to change the <body onload="mkSidebar('data');">
line to use either the DOMContentLoaded
event or the window.load
event instead. This is because inline JavaScript will not be executed in Chrome extensions due to security reasons.
The suggested approach is to wait for the DOMContentLoaded
event or the window.load
event to fire, and then execute the mkSidebar
function from within an event listener. This ensures that the code is targeting the correct window (the popup window) and that it is executed after the DOM has been fully loaded.
Ask anything...