Reputation: 13
So I'm trying to make a chrome extension. My code works fine when I run it as a normal html page, but when I use browser action, my enable/disable button doesn't work. It doesn't do anything when I press enable (Which it should switch to disable). Was wondering if there is something I don't know about like permissions or something. I haven't set any permissions in my json page but I didn't think it was the problem. Was wondering if you guys can take a look and see what I'm missing. Here's my code.
<html>
<head>
<link rel="stylesheet" type="text/css" href="nosidebar.css">
<script type="text/javascript">
function enableBtn(){
document.getElementById("btn1").style.display = "none";
document.getElementById("btn2").style.display = "";
return false;
}
function disableBtn(){
document.getElementById("btn2").style.display = "none";
document.getElementById("btn1").style.display = "";
return false;
}
</script>
</head>
<body>
<div id="button">
<a href="javascript:void(0)" class="myButton1" title="Click to disable" id="btn1" style="display:;" onclick="enableBtn(); return false;">Enabled</a>
<a href="javascript:void(0)" class="myButton2" title="Click to enable" id="btn2" style="display:none;" onclick="disableBtn(); return false;">Disabled</a>
</div>
<div id="text">
You must refresh the page for the change to take effect.
</div>
</body>
</html>
Thanks to @duskwuff I have fixed my problem. I created a separate js file and used the following code.
function enableBtn(){
document.getElementById("btn1").style.display = "none";
document.getElementById("btn2").style.display = "";
return false;
}
function disableBtn(){
document.getElementById("btn2").style.display = "none";
document.getElementById("btn1").style.display = "";
return false;
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("btn1").addEventListener("click", enableBtn);
document.getElementById("btn2").addEventListener("click", disableBtn);
});
Upvotes: 1
Views: 121
Reputation:
HTML pages used as part of Google Chrome extensions always have a Content Security Policy set which prohibits inline scripts, both in attributes (e.g. onclick
) and inline <script>
tags. You will need to define these scripts in a separate Javascript file and bind event handlers in that script, e.g.
<script src="nosidebar.js"></script>
and in that file:
function enableBtn() { ... }
function disableBtn() { ... }
document.getElementById("btn1").addEventListener("click", enableBtn);
document.getElementById("btn2").addEventListener("click", disableBtn);
For more information on Content Security Policy and how it relates to Chrome extensions, please refer to:
https://developer.chrome.com/extensions/contentSecurityPolicy
Upvotes: 5