This question already has answers here:
onclick or inline script isn't working in extension
(5 answers)
How to open the correct devtools console to see output from an extension script?
(3 answers)
Closed 9 days ago.
I'm trying to build a chrome extension for the first time. I have a simple button, that launches a youtube webpage. But I can't seem to figure out why the button's event listener is never fired.
The index.html:
<!DOCTYPE html>
<html>
<head>
<style>
button {
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<button id="youtube-button">YouTube</button>
<script>
document.getElementById("youtube-button").addEventListener("click", function() {
console.log('clicked youtoob button!')
window.open("https://www.youtube.com/");
});
</script>
</body>
</html>
The manifest:
{
"manifest_version": 2,
"name": "YouTube Button",
"description": "A button that opens YouTube",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "index.html"
},
"permissions": [
"activeTab"
]
}
The console.log('clicked youtoob button!') is never fired inside the developer console when I click the button.
What am I doing incorrectly?
The chrome console indicates that you are facing a problem similar to this Script causes “Refused to execute inline script: Either the 'unsafe-inline' keyword, a hash… or a nonce is required to enable inline execution”.
To see your error precisely, you can right click and do 'inspect' on your button.
As indicated, the cleanest way to do this is do create a new file in your directory, called openYoutube.js for example that contains this:
document.getElementById("youtube-button").addEventListener("click", function() {
console.log('clicked youtoob button!')
window.open("https://www.youtube.com/");
});
and then call it in your html file like this
<script src="openYoutube.js"></script>
DevTools should have printed the following error:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem:". Either the 'unsafe-inline' keyword, a hash ('sha256-HikUgQ3MQB9uiD//iKT5jDhdLF+X0toeRrwaYXjWvhY='), or a nonce ('nonce-...') is required to enable inline execution.
It is caused by embedding script in html.
index.html
<!DOCTYPE html>
<html>
<head>
<style>
button {
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<button id="youtube-button">YouTube</button>
<script src="index.js"></script>
</body>
</html>
index.js
document.getElementById("youtube-button").addEventListener("click", function() {
console.log('clicked youtoob button!')
window.open("https://www.youtube.com/");
});
Related
I am trying to make a function execute when clicking the extension's icon in the toolbar(on the right corner). I added chrome.browserAction.onClicked.addListener in background.js file but it is not working. please help me.
Ultimately, My goal is to set a different icon by HTML element in http://localhost:3000 that I use in the iframe tag.
(check there is a specific element in localhost:3000 -> set icon)
The reference that I follow:
https://developer.chrome.com/extensions/samples#search:a%20browser%20action%20which%20changes%20its%20icon%20when%20clicked
my code is below.
manifest.json
{
"name": "test",
"version": "1.0",
"description": "test",
"manifest_version": 2,
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"storage"
],
"browser_action": {
"default_title": "test",
"default_popup": "popup.html"
}
}
background.js
chrome.browserAction.onClicked.addListener(() => {
console.log('test for browser action');
});
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<iframe src="http://localhost:3000" width="400" height="600"></iframe>
<script src="./background.js" charset="UTF-8"></script>
</body>
</html>
Specifying default_popup in manifest.json disables chrome.browserAction.onClicked event.
Solution: simply put the code in popup.js and load it as any other script in popup.html.
popup.html
<script src=popup.js></script>
</body>
</html>
popup.js
console.log('This will run every time the popup is opened');
To inspect the popup and its console, right-click inside the popup, then click "inspect".
Note that you don't need the background script for this. The background script runs in a hidden background page so it should never be used anywhere else. Remove it from popup.html.
P.S. You're using the wrong reference extension. Search for popup.html using the built-in browser search via Ctrl-F (not the search input on the page).
This question already has answers here:
onclick or inline script isn't working in extension
(5 answers)
How to access the webpage DOM/HTML from an extension popup or background script?
(2 answers)
Closed 1 year ago.
I oftenly waste my time by reading youtube comments while studying. So i came with an idea, decided to make an extension which was gonna hide the comments section. I found the ID of element, made a simple extension but it didn't work cause of the following error:
My extension's html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Comminator | Youtube Comment Terminator</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<button id="main" onclick="hide()">Terminate</button>
<script type="text/javascript">
var comments = document.getElementById("comments"); //"comments" is the ID of comments section in youtube
function hide() {
comments.style.display = "none";
}
</script>
</body>
</html>
Json File:
{
"manifest_version": 2,
"name": "Comminator",
"description": "Youtube Comment Hider",
"version": "1.0",
"icons": {"128": "icon_128.png"},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["activeTab"]
}
Are we not able to interference with the elements ? Doesn't chrome allow it ?
It seems to not like the inline code onclick="hide()", so use eventListener instead
there are multiple comments with id=comment. They cannot be accessed by getElementById
const comments = document.querySelectorAll("[id=comment]"); //"comment" is the ID of each comment in youtube
document.getElementById("main").addEventListener("click", function(e) {
e.preventDefault(); // in case the button ends up in a form
comments.forEach(comment => comment.style.display = "none"))
})
Alternatively just have a bookmarklet:
javascript:(() => document.querySelectorAll("[id=comment]").forEach(comment => comment.style.display = "none"))()
Make a bookmark and change the URL to the above and it will hide when you click it
I am trying to make a function execute when clicking the extension's icon in the toolbar(on the right corner). I added chrome.browserAction.onClicked.addListener in background.js file but it is not working. please help me.
Ultimately, My goal is to set a different icon by HTML element in http://localhost:3000 that I use in the iframe tag.
(check there is a specific element in localhost:3000 -> set icon)
The reference that I follow:
https://developer.chrome.com/extensions/samples#search:a%20browser%20action%20which%20changes%20its%20icon%20when%20clicked
my code is below.
manifest.json
{
"name": "test",
"version": "1.0",
"description": "test",
"manifest_version": 2,
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"storage"
],
"browser_action": {
"default_title": "test",
"default_popup": "popup.html"
}
}
background.js
chrome.browserAction.onClicked.addListener(() => {
console.log('test for browser action');
});
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<iframe src="http://localhost:3000" width="400" height="600"></iframe>
<script src="./background.js" charset="UTF-8"></script>
</body>
</html>
Specifying default_popup in manifest.json disables chrome.browserAction.onClicked event.
Solution: simply put the code in popup.js and load it as any other script in popup.html.
popup.html
<script src=popup.js></script>
</body>
</html>
popup.js
console.log('This will run every time the popup is opened');
To inspect the popup and its console, right-click inside the popup, then click "inspect".
Note that you don't need the background script for this. The background script runs in a hidden background page so it should never be used anywhere else. Remove it from popup.html.
P.S. You're using the wrong reference extension. Search for popup.html using the built-in browser search via Ctrl-F (not the search input on the page).
This question already has answers here:
onclick or inline script isn't working in extension
(5 answers)
Closed 5 years ago.
So I made a little html file the other day and it's just a page that has a clock, gif background, and a search bar that searches Google.
I had it all working as an html file earlier but then I wanted to make it into a chrome extension. I had to make a manifest.js file and put the scripts in a separate file too and then the search wasn't working anymore.
I really have no clue what I did wrong.
Here's my manifest file:
{
"name": "THE GOODEST",
"description": "Overrides the new tab page",
"version": "0.1",
"icons": {"48": "icon.png"},
"incognito": "split",
"chrome_url_overrides": {
"newtab": "newTab.html"
},
"manifest_version": 2
}
Here's my html file:
<!DOCTYPE html>
<html>
<title>New Tab</title>
<body onload = "resizeWindow()">
<iframe src="http://free.timeanddate.com/clock/i63s4yyj/n224/ahl/avb/pa10/tt0/tw1/tm1/ts1" frameborder=0 width="195" height="37" style="position:fixed; bottom: 10px"></iframe>
<input id="searchBar">
<button onclick="search()">Search</button>
<script type = "text/javascript" src = "scripts.js"></script>
</body>
</html>
And here's my script:
function search() {
var text = document.getElementById("searchBar").value;
window.open("https://www.google.com/search?q=" + text)
}
As stated by #Deliaz in the comments, inline javascript isn't allowed in chrome extension because of strict environment isolation.
Change this: <button onclick="search()">Search</button> to: <button id='searchButton'>Search</button>
and place some code in your separate script.js file that attaches an eventlistener to your search button on the click action.
// Triggers when all DOM elements are loaded
document.addEventListener('DOMContentLoaded', function(event) {
// Attaches listener for click event on search button
document.querySelector('#searchButton').addEventListener('click', function(e) {
return search();
});
});
function search() {
var text = document.getElementById("searchBar").value;
window.open("https://www.google.com/search?q=" + text)
}
Alternatively you could also use the search event on the input field: https://developer.mozilla.org/en-US/docs/Web/Events/search
I'm developing a chrome extension which involves getting selected text of the current tab. Here is the html file that I use:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.getElementById("output").value = selection[0];
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
It doesn't work, why? As followed is the error message from Chrome App & Extension Developer Tool, some of these error messages are cut with ellipses, sorry I haven't figured out how to view the full error messages here, view details only gives me the stack track, not the full error message.
As #Xan suggested, the method mentioned before (you can find it here) is overcomplicated. To get it to work, there are only two things to do:
Change value to innerHTML in document.getElementById("output").value
Add an activeTab permission in manifest.json file
Here is the complete source code, three files in total.
manifest.json
{
"manifest_version": 2,
"name": "sample",
"description": "A sample extension to get the selected text",
"version": "1.0",
"icons": {
"16": "img/icon16.png",
"48": "img/icon48.png",
"128": "img/icon128.png"
},
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="popup.js"></script>
<title></title>
</head>
<body>
<div id="output"></div>
</body>
</html>
popup.js
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.getElementById("output").innerHTML = selection[0];
});
Your original approach was correct (and probably taken from this question).
It had 2 problems:
Inline scripts (<script>...</script>) are not allowed; it's fixed by putting code in a separate file, say, popup.js.
You need permission to access a page for content script injection; in your particular case, there's a specific permission, "activeTab", that does it in a transparent and painless way with no security warnings. When your extension is invoked (by clicking on the button), you are given access to the current tab.
With those fixed, your "direct" approach works.
By the way, to debug such problems in future, you need to inspect the popup page.
As for your own answer, you are over-complicating things a lot.
You don't need an Event page is this particular case; your popup can call executeScript and listen to messages. There are cases when you do need it, specifically when you can't guarantee that popup is open when content script sends messages; but here you can guarantee it.
Supposing you need the event page, consider not using getBackgroundPage to call a method in it - it tightly couples code; you can instead send a message. sendResponse can be used to pass the results back, even asynchronously.
Finally, your schema is confusing with respect to content.js. Only one copy of it executes, in a special context that is attached to the target page (and not in the extension context).