Functions aren't working in Chrome Extension [duplicate] - javascript

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

Related

Chrome Extension .addEventListener never fired [duplicate]

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/");
});

I can't effect DOM cause of "Refused to execute inline event handler" error. -Chrome Extensions [duplicate]

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

Chrome Extension wont run .JS on button click

thank you in advance for the help!
Problem Statement: I am trying to create a chrome extension that allows a user to input a value in a textbox and then navigate to specific link based on the value in the textbox after hitting a submit button. At work, we have ticket numbers that I can view on a webpage. the start of the link is always the same, followed by the ticket number. For some reason, when I execute my extension, it will ask for a value, but after hitting submit it displays my js code instead of navigating to a web page. Please advise.
Below is my code, I have removed any IP related to my work:
manifest:
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"browser_action": {
"default_popup": "popup.html",
"default_title": "popup"},
"manifest_version": 2
}
popup.html:
<!DOCTYPE html>
<html>
<body style="width: 300px">
<input type="text" id="user_input" name="user_input"><br><br>
<button id="clickme">Run</button>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
popup.js
function Search() {
var Y = (document.getElementById("user_input").value).trim();
window.open("https://www.w3schools.co"+ Y);
}
document.getElementById('clickme').addEventListener('click', Search);
If any clarification is required, please let me know.
EDIT: the above code is how I got this to work. this will open a popup when the extension is clicked on and allow a user to input a value. once the run button is clicked, the value will be passed to the popup.js and open a new window. thank you to everyone who helped!
The problem is you have the default_popup already defined. So you cannot have a listener for browserAction.onClicked. More info here
You can add the code you have under chrome.browserAction.onClicked.addListener directly to popup.js i.e. add the following directly to popup.html and create a popup.js
popup.html:
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<p>Some Content ..</p>
</body>
</html>
popup.js:
var NUM = 'm';
chrome.tabs.create({url: 'http://google.co' + NUM}, callback);
function callback(data) {
console.log(data);
}
});

How to get selected text in chrome extension development?

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).

Code clears page instead of going to new site

I've been trying to create this chrome extension that you enter an address and click a button and it goes there. This may sound like a stupid idea but somehow a server block on a site is bypassed by chrome extensions. This is my current code:
<html>
<head>
<title>Website Opener</title>
<style type="text/css">
body
{
font-family: "Lucida Grande";
height: 100%;
}
</style>
<script>
$(document).ready(function() {
$('#url').change(function() {
var newurl = $('#url').val();
$('a.target').attr('href', newurl);
});
});
</script>
</head>
<body>
<form>
<input type="text" id='url' value='http://'>
<br>
<p><a class="target" href="">Go!</a></p>
</form>
</body>
</html>
What it currently does is just make the page blank or clear the input box instead of going to the new site.
I have tried javascript .open() method, this is trying jQuery. I'm mainly wondering if there are any other ways to do this or if I'm missing something.
This will help you:
Place jQuery to your <head> or in the end of your page, but before your code.
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
Then rewrite your code to use a keypress event:
$(document).ready(function() {
$('#url').keypress(function() {
$('.target').attr('href', this.value)
})
});
FYI: change event will happen when you changed a value of your input and set the focus out of it. So if you type an url and place your mouse cursor on the link and press it, change event will trigger AFTER your click. So be careful with those events.
UPDATE:
I just saw that you're doing an extension for GC.
The best practices tell us to divide application by layers' aim. HTML and JS should be separated.
In your manifest.json you have to add
"js": ["jquery.js", "content_script.js"]
and move your JavaScript logic from HTML file to the content_script.js.

Categories

Resources