Javascript in Google Chrome popup extension not running - javascript

Hi I have run into a very weird problem.
I have a basic chrome extension which has a default popup.html document defined as follows:
<html>
<head>
<script type="text/javascript">
function disp() {
document.getElementById("test").innerHTML = "Bye";
}
</script>
</head>
<body>
<p id="test">Hello</p>
<button type="button" onclick="disp()">'Twas Nice to meet you</button>
</body>
</html>
Upon running the html file independently in a browser, it behaves as expected: clicking on the button changes the text of the p tag. However, from withing the chrome extension, in the popup the button does not seem to respond
Is this something to do with popups in general or something specific to my code?

Although you've found out you can circumvent the inline script "issue" (it is a security feature), below is what it would look like if you did not do that. This shows both how to call a notification and a "window"-based dialog.
manifest.json
{
"name": "Hello World!",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"notifications",
"create",
"tabs"
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started with Extension's Popup</title>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<!-- JavaScript and HTML must be in separate files for security. -->
<script src="popup.js"></script>
</head>
<body>
<div style="text-align: center;">
<button type="button" id="click">Show Notification</button>
<button type="button" id="dialog">Show Dialog</button>
</div>
</body>
</html>
dialog.html
<!doctype html>
<html>
<head>
<title>Dialog Prompt - Chrome</title>
<style>
body {
overflow: hidden;
margin: 0px;
padding: 0px;
background: white;
}
p {
text-align: center;
padding: 20px;
}
</style>
</head>
<body>
<p>This is a dialog prompt.</p>
</body>
</html>
popup.js
var notifier,
dialog;
function showNotify() {
var notify;
if (window.webkitNotifications.checkPermission() == 0) {
notify = window.webkitNotifications.createNotification(
"",
'Notification Test',
'This is a test of the Chrome Notification System. This is only a test.'
);
notify.show();
} else {
window.webkitNotifications.requestPermission();
}
}
function showDialog(){
chrome.windows.create({
url: 'dialog.html',
width: 200,
height: 120,
type: 'popup'
});
}
function init() {
clicker = document.querySelector('#click');
dialog = document.querySelector('#dialog');
clicker.addEventListener('click', showNotify, false);
dialog.addEventListener('click', showDialog, false);
}
document.addEventListener('DOMContentLoaded', init);
You can find the files to download here:
http://jfcoder.com/projects/chrometestdialogs/

manifest_version 2 doesn't allow user to enter the function inside the html file for security purpose, should we need to write all the function in separate file and import it to that html file like below
<head>
<script src="yourjsfile.js"></script> //All our functions are defined here
<script src="jquery.js"></script> // This is the jquery
</head>
and the function calling are not allowed here like onclick, onkeydown,onkeyup, etc...
<body>
<p id="test">Hello</p>
<button type="button" id="btn">Twas Nice to meet you</button>
</body>
In above "onclick="disp()" not allowed, and should assign a id
so should we need to create the event and definition must create from the .js file
So you should write a js file like below yourjsfile.js
document.addEventListener('DOMContentLoaded', function () {
$("#btn").on("click",function(){
disp();
});
});
function disp() {
document.getElementById("test").innerHTML = "Bye";
}

Related

How to grab page content by class in Chrome extension?

I want to grab content from page by class. I wrote chrome extension, but I don't get the contents of the element. I recieved [object Object] in textarea. I tried to get the page title when I wrote chrome.runtime.sendMessage(document.title); in payload.js and it's work, but not work when I try to get content by class. Please tell me how to fix my solution?
manifest.json
{
"manifest_version": 2,
"name": "Scrap",
"description": "Scrap",
"version": "1.0",
"author": "",
"background": {
"scripts": ["popup.js"],
"persistent": true
},
"permissions": [
"tabs",
"http://*/",
"https://*/"
],
"browser_action": {
"default_icon": "logo.png",
"default_popup": "popup.html"
}
}
popup.js
window.addEventListener('load', function (evt) {
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
file: 'payload.js'
});;
});
chrome.runtime.onMessage.addListener(function (message) {
document.getElementById('json-content').innerHTML = message;
});
popup.html
<!doctype html>
<html>
<head>
<title>Scrap</title>
<script src="popup.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<style>
.container {
min-width: 500px;
padding: 1rem 1.5rem;
}
</style>
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<label for="exampleFormControlTextarea1">JSON</label>
<textarea class="form-control" id="json-content" rows="3"></textarea>
</div>
</form>
</div>
</body>
</html>
payload.js
chrome.runtime.sendMessage(document.getElementsByClassName("something"));
page for grab
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Scrap</title>
<script src="popup.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<style>
.container {
min-width: 500px;
padding: 1rem 1.5rem;
}
</style>
</head>
<body>
<div class="container">
<h1>Test</h1>
<p class="something">Text</p>
</div>
</body>
</html>
In your payload.js you are not getting the text of the class but the elements with that class, so it shows that it is an object. Also, getElementsByClassName returns multiple results that you need to go threw.
I would do something like this in my payload.js file:
var result = "";
var somethings = document.getElementsByClassName("something");
for (var i = 0; i < somethings.length; i++) {
result += somethings[i].textContent;
}
chrome.runtime.sendMessage(result);
Note that this will return all the text inside the elements that have that class.

Chrome extension: How to open a specified link in a new tab by clicking a button in the html popup?

I'm trying to dip my feet into the water of the pool that is creating chrome extensions. I tried to start off with something I thought would be simple but it has proven to stump me as I don't really know where I can read information on this sort of thing.
Anyhow, currently my goal is to have a chrome extension that does the following:
You click the extension icon -> an HTML popup file opens displaying a singular button -> when you click this button it opens a specified link in a new chrome tab and changes that to be your active tab.
From my searching, I have found that I might have to use a background script so that I don't violate a policy regarding Manifest version 2 or something of the sorts, I tried it and it didn't really work for me. I really don't want to wander into creating a whole new script if that's not the problem.
Here's my manifest.json file followed by my popup.html file.
{
"manifest_version": 2,
"name": "strong text",
"author": "authorname",
"description": "desctext",
"version": "1.4",
"permissions": [
"tabs"
],
"icons": { "16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png" },
"browser_action": {
"default_popup": "popup.html"
}
}
<!doctype html>
<html>
<head>
<title>Hovertext</title>
<script src="popup.js"></script>
</head>
<body>
<div id="header">
<h1>Header</h1>
</div>
<div id="divider">
<p><button type="button" id="buttonA">Button Text</button>
<script>
var button1 = document.getElementById("buttonA");
button1.addEventListener("click", function() {
chrome.tabs.create({url: "http://www.google.com/"});
});
</script>
</div>
<div id="footer">
footer stuff here
</div>
</body>
<style>
body {
background-image: url("https://s-media-cache-ak0.pinimg.com/736x/51/3e/4f/513e4f5274ec48f29b894b0b8409658f.jpg");
}
#header {
background-color:rgb(96, 222, 72);
text-align:center;
padding:1px;
}
#footer {
background-color:rgb(96, 222, 72);
clear:both;
text-align:center;
padding:1px;
}
#divider {
text-align:center;
}
#buttonA {
color:white;
background-color:rgb(0, 152, 255);
border-width:3px;
border-color:white;
}
#buttonA:hover {
color:rgb(0, 152, 255);
background-color:white;
border-width:3px
border-color:rgb(0, 152, 255);
}
</style>
</html>
I'm new to this type of stuff and stack-overflow in general so if I didn't clarify something correctly just let me know, Thanks for the help in advance!
A simple code to open new tab on click some button. Try to use it on your extension.
manifest.json:
{
"name": "Test",
"version": "1.1",
"description":
"Description",
"permissions": [
"notifications",
"fontSettings"
],
"options_page": "options.html",
"manifest_version": 2
}
option.html:
<!doctype html>
<html>
<head>
<title>Demo</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="options.js"></script>
</head>
<body>
<input type="button" id="btnOpenNewTab" value="Click to open new tab"/>
</body>
</html>
option.js:
window.addEventListener('DOMContentLoaded', function() {
// your button here
var link = document.getElementById('btnOpenNewTab');
// onClick's logic below:
link.addEventListener('click', function() {
var newURL = "http://stackoverflow.com/";
chrome.tabs.create({ url: newURL });
});
});
You use this source code for your popup's button
window.opener.open("http://www.google.com/");

How to add a click event to a button in a chrome extension?

I am trying to create a very simple chrome extension that open multiple tabs of LinkedIn searching different keywords that I type in.
Since this is my first extension, most of my codes are based on this extension, which is very similar to my idea.
The problem is when I click my "search" button, nothing happens. I just started coding for a week so I'd greatly appreciate any help!
Besides knowing what is wrong with the codes, is a background script necessary in this case?
Thanks!
Here are my codes:
Manifest.json
{
"manifest_version": 2,
"name": "Search Assistant",
"description": "This extension makes LinkedIn Search easy.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["myscript.js"]
}
],
"chrome_url_overrides" : {
"newtab": "newtab.html"
},
"background": {
"scripts": ["bg.js"]
}
}
Popup.html
<!doctype html>
<head>
<style type="text/css">
body{
font family: Helvetica, Arial, sans;
font-size: 12px;
}
#instruction{
padding-bottom: 10px;
}
#searcharea{
padding-bottom: 10px;
}
#search{
padding-bottom: 10px;
float: left;
}
#companies{
white-space: nowrap;
overflow:auto;
}
</style>
<style type="text/javascript" src="popup.js"></style>
</head>
<body>
<div id="instruction">Companies you want to search for:</div>
<div id="searcharea"><textarea rows="20" cols="80" id="companies" wrap="soft" tabindex="1"></textarea></div>
<div id="search">
<button id="btn1" tabindex="2">Search</button>
</div>
<p id="demo"></p>
</body>
</html>
Popup.js
document.addEventListener('DOMContentLoaded', function (){
document.getElementById('btn1').addEventListener('click', loadSites);
document.getElementById('companies').focus();
});
function loadSites(e){
var companies = document.getElementById('companies').value.split('\n');
for(var i=0; i<companies.length; i++){
thecompany = companies[i].trim();
thesearchurl = 'https://www.linkedin.com/vsearch/c?type=companies&keywords=' + thecompany;
chrome.extension.create({url: thesearchurl, selected:false})
}
}
You have 2 slight errors right now. Firstly you should use script-tag instead of style to include javascript files. Second: it is better to load javascript after your page is ready. To fix these follow steps below
Remove line <style type="text/javascript" src="popup.js"></style>
Add this <script type="text/javascript" src="popup.js"></script> to a line right before </body>.

Chrome apps <webview> tag can't change background-color

I'm trying to make a google app extension that loads a external webpage having the app frameless. At launch of the program it takes few seconds for the page to load and the it's all white.
Whatever I do I can't change the background color.
Bellow is a part of the code
Any ideas?
manifest.json
{
"name": "Stats ",
"description": "My Stats",
"manifest_version": 2,
"version": "1.0",
"icons": {
"128": "128.png"
},
"app": {
"background": {
"scripts": ["main.js"]
}
},
"permissions": [
"webview"
]
}
main.js
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create("index.html",
{ frame: "none",
id: "framelessWinID",
innerBounds: {
width: 360,
height: 300,
left: 600,
minWidth: 220,
minHeight: 220
}
}
);
});
index.html
<html>
<head>
<title>Stats</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script>
var wv = document.querySelector('webview');
wv.addEventListener('loadcommit', function() {
wv.insertCSS({
code: 'body { background: red !important; }',
runAt: 'document_start'
});
});
</script>
</head>
<body>
<div id="top-box" ></div>
<webview src="" style="width:500px; height:500px;" ></webview>
</body>
</html>
The first issue here is that Google Chrome apps have a Content Security Policy that blocks inline javascript, so you will need to move your script out to its own file.
The second issue is that the insertCSS function inserts the CSS into the page that is loaded in the webview, not the webview itself.
I'm not sure if it's possible to set a background style on the webview itself. If your goal is to not have a white box in your app while the page is loading, another approach might be to have a "please wait while the page loads" div overlaying the webview that you show/hide when the page is loading.
index.html
<html>
<head>
<title>Stats</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="index.js"></script>
</head>
<body>
<div id="top-box" ></div>
<webview src="..." style="width:500px; height:500px;" ></webview>
<div id="loading" style="background: red; position:fixed; z-index:999; left:0%; top:0%; width:100%; height:100%;">
Loading...
</div>
</body>
</html>
index.js
onload = function() {
var wv = document.querySelector('webview');
var loading = document.querySelector('#loading');
wv.addEventListener('loadstart', function() {
loading.style.display="block";
});
wv.addEventListener('loadstop', function() {
loading.style.display="none";
});
};

Run Javascript in Chrome Extension -> Basic?

I get the feeling I'm missing something very obvious, but I've been looking everywhere and can't seem to make this work. In short, I want to turn a small Javascript script into a chrome extension to make it easier to use.
The script just reads text from a textArea, modifies the script and outputs it into a div. It works perfectly with any browser when running standalone, but doesn't seem to want to work when ran as a Chrome extension
Here are the files (I'm basically trying to convert the example):
Thanks!
manifest.json
{
"manifest_version": 2,
"name": "One-click Kittens",
"description": "This extension demonstrates a 'browser action' with kittens.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"https://secure.flickr.com/"
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
min-width: 357px;
overflow-x: hidden;
}
img {
margin: 5px;
border: 2px solid black;
vertical-align: middle;
width: 75px;
height: 75px;
}
</style>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: http://developer.chrome.com/extensions/contentSecurityPolicy.html
-->
<script src="popup.js"></script>
</head>
<body>
<textarea id="source">Text Entry.</textarea>
<button onclick="main()" id="buttons">Generate</button>
<div id="result">
</div>
</body>
</html>
popup.js
function main() {
var source = document.getElementById('source').value;
document.getElementById("result").innerHTML = source;
}
According to chrome extension documentation,
Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).
Read: http://developer.chrome.com/extensions/contentSecurityPolicy.html#JSExecution
Use in popup.js as
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', main);
});
function main() {
var source = document.getElementById('source').value;
document.getElementById("result").innerHTML = source;
}

Categories