问题
I was making a Chrome extension, for which I have an html file, a JavaScript file which opens a modified link in a new tab, the manifest file and the icon.
It works fine but now I want the javascript function to work only when the user clicks a button. So I made a button in the html file, put the js code inside a function and called the function using onclick
.
But for some reason, it is not working. On clicking the button nothing seems to happen. I have tried reloading the extension. Also, I took a working example of a simple program in which on clicking the button, a simple "Hello world" message is displayed using alert().
This works fine when I open the html page directly in chrome but when I replaced this with the function that I made, nothing seems to happen on clicking.
Can someone please find the bug/problem?
The urltry.html file is:
<!DOCTYPE html>
<html>
<button onclick="editorial()">View Editorial</button>
<script>
function editorial()
{
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var tab_url=tabs[0].url;
var new_url=tab_url.slice(11);
chrome.tabs.create({ url:"http://www.discuss." + new_url});
});
}
</script>
</html>
回答1:
Due to the default Content Security Policy (CSP) in Google Chrome extensions, the following is disallowed:
- Eval and related functions
- Inline JavaScript
The suggestion, as provided by Google Chrome Extensions documentation on SCP is to place the code to a separate file and use proper binding to click event from JavaScript. See below.
Your HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="editorial.js"></script>
</head>
<body>
<button id="viewEditorial">View Editorial</button>
</body>
</html>
Your JavaScript file, editorial.js
function editorial() {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var tab_url=tabs[0].url;
var new_url=tab_url.slice(11);
chrome.tabs.create({ url:"http://www.discuss." + new_url});
});
}
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('viewEditorial');
if (btn) {
btn.addEventListener('click', editorial);
}
});
Note: don't forget that you need to declare "tabs"
permission to be able to modify the URL. See the tabs documentation.
回答2:
You must put your button inside the body tag, otherwise many bad things can happen and probably the browser goes in the quirks mode.
Solution:
<!DOCTYPE html>
<html>
<head>
<script>
function editorial()
{
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var tab_url=tabs[0].url;
var new_url=tab_url.slice(11);
chrome.tabs.create({ url:"http://www.discuss." + new_url});
});
}
</script>
</head>
<body>
<button onclick="editorial()">View Editorial</button>
</body>
</html>
回答3:
You can try with this,
<body>
<button onclick="javascript:editorial()">View Editorial</button>
</body>
This will work in Microsoft EDGE browser also.
来源:https://stackoverflow.com/questions/25580851/unable-to-call-javascript-function-in-html-on-button-click