Data not passing from popup to background in chrome extension - javascript

I think I got the hang of it but it's just not working... and I can't figure out why.
Manifest:
{
"name": "Dummy Extension",
"description": "Dummy Extension Description",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Dummy Extension",
"default_popup": "popup.html"
},
"manifest_version": 2,
"content_scripts": [ {
"js": [ "jquery.min.js", "background.js" ],
"matches": [ "http://*/*", "https://*/*"]
}]
}
Background:
chrome.extension.onMessage.addListener( function(request,sender,sendResponse)
{
if( request.greeting === "GetURL" )
{
var tabURL = "Not set yet";
chrome.tabs.query({active:true},function(tabs){
if(tabs.length === 0) {
sendResponse({});
return;
}
tabURL = tabs[0].url;
sendResponse( {navURL:tabURL} );
});
}
}
Popup.html
<!DOCTYPE html>
<head>
<script src='popup.js'></script>
<script src='jquery.min.js'></script>
</head>
<body>
Hello World!
<br />
<input id="tabURL" type="text" />
<br />
<input value="SEND!" type="button" id="send" />
</body>
</html>
And popup.js
function getURL() {
chrome.extension.sendMessage({greeting: "GetURL"},
function (response) {
tabURL = response.navURL;
$("#tabURL").val(tabURL);
});
}
$("#send").click(getURL());
I just can't figure out whats wrong, jquery is defined, I get no console errors.
Any help would be great!

$("#send").click(getURL()); gets executed before DOM is fully constructed and fails. Also, you need to pass the reference to getURL, not execute it.
To fix:
$(document).ready(function(){
$("#send").click(getURL);
});
By the way, you may be looking in the wrong console for errors. See this debugging tutorial for popups.

Related

Edge extension to rename tab title not working

I am trying to write an Edge extension that changes the title of a tab.
Here is what I've tried but it doesn't seem to change the tab's title.
When I add alert(tab.title) it does seem like it has changed.
Manifest.json
{
"name": "My Tab",
"version": "2.0.0",
"description": "Simple Microsoft Edge Extension",
"manifest_version": 2,
"author": "abc",
"browser_action": {
"default_popup": "bg.html",
"default_title": "Hello World"
},
"permissions": [
"tabs",
"<all_urls>"
],
"background": {
"page": "bg.html",
"persistent": true
}
}
bg.html
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
</head>
<body>
<div>
<h3>Click the button to get the page URL...<h3><br>
<button id="btn1">click me</button>
<input type="text" id="txt1" style="width:300px">
</div>
<script type="text/javascript" src="background.js"></script>
</body>
</html>
background.js
var btn= document.getElementById("btn1");
btn.addEventListener("click", function(){
abc();
});
function abc()
{
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs)
{
var tab = tabs[0];
var title = document.getElementById("txt1").value;
tabs[0].title = title;
tab.reload();
});
}
Any idea?
Here's how I change the tab's title. It involves a content script. Also, I used sendMessage in background.js to pass the title into content script. Don't forget to add the content script to your manifest.json.
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
if (request.title)
{
document.title = request.title;
}
})
background.js
var btn = document.getElementById("btn1");
btn.addEventListener("click", function(){
abc();
});
function abc()
{
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs)
{
var tab = tabs[0];
var title = document.getElementById("txt1").value;
chrome.tabs.sendMessage(tabs[0].id, {title: title}, function(response){});
});
}
manifest.json
{
"name": "My Tab",
"version": "2.0.0",
"description": "Simple Microsoft Edge Extension",
"manifest_version": 2,
"author": "abc",
"browser_action": {
"default_popup": "bg.html",
"default_title": "Hello World"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"permissions": [
"tabs",
"<all_urls>"
],
"background": {
"page": "bg.html",
"persistent": true
}
}

Chrome Extension Event Listener Not Working

I am trying to create a sample simple chrome extension . I need to create a event listener for button. It is not working don't know why? I tried jQuery and javascript to write event listener still not triggering. Since the log in document ready is working i think there is no issue with Manifest.
javascript
$(document).ready(function() {
$("#rama").click(function() {
console.log('afawfafaf');
});
console.log("rambo adloaded!");
});
HTML
<HTML>
<HEAD>
<h1>Easy </h1>
</HEAD>
<style type="text/css">
body {
min-width: 300px;
}
</style>
<BODY>
<button type="button" id="rama">fe!</button>
</BODY>
</HTML>
Manifest
{
"update_url": "https://clients2.google.com/service/update2/crx",
"manifest_version": 2,
"name": "easy",
"description": "",
"version": "1.1",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery-3.2.1.min.js", "content.js"],
"run_at": "document_end"
}],
"permissions": [
"activeTab",
"https://ajax.googleapis.com/"
],
"browser_action":
{
"default_icon": "rambo.png",
"default_popup": "easy.html"
},
"background":
{
"scripts": ["jquery-3.2.1.min.js"]
}
}
Any Idea what i am Missing ??

Messages not exchanged between content scripts, background.js and popup.js

I am trying to make a google-chrome extension which fetches selected text from the webpage and displays it in the popup. I've read google-chrome docs and have followed many questions but I have been unable to resolve this issue. Selected text cannot be sent to background.js and furthur to popup.js.
manifest.json:
{
"name": "Wordomania",
"version": "1.0",
"manifest_version": 2,
"description": "Displays word on popup",
"icons": {
"16": "images/W.png"
},
"background": {
"scripts": [
"jquery-3.3.1.js",
"background.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["content.js"]
}
],
"permissions": [
"background",
"tabs",
"http://*/*",
"https://*/*",
"activeTab"
],
"browser_action": {
"default_icon": "images/W.png",
"default_title": "Wordomania"
}
}
background.js :
chrome.browserAction.onClicked.addListener(function (tab) {
console.log('Extension button clicked');
chrome.tabs.sendMessage(tab[0].id, {
action: 'sendWord'
}, function (wordObject) {
console.log('Word received');
let obj = {
word: wordObject.word,
from: 'back'
};
chrome.runtime.sendMessage(obj, function (status) {
console.log(status);
});
});
});
content.js :
function getSelectionText() {
let text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type !== 'Control') {
text = document.selection.createRange().text;
}
return text;
}
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.action === 'sendWord') {
let text = getSelectionText();
sendResponse({word: text});
}
});
popup.html :
<!DOCTYPE html>
<html>
<head>
<title>Wordomania</title>
<script src="popup.js"></script>
</head>
<body>
<h1><p id="word"></p></h1>
<div id="body-of-popup"></div>
</body>
</html>
Help required!
Basically, you will need to do a few changes in your approach. Since, we can have only one event at a time assoiciated with the browserAction either popup or chrome.browserAction.onClicked. In your case you have a popup assoiciated so you can not use chrome.browserAction.onClicked.
But still you can achieve what you want using the code below.
// Add below code in your popup.js
document.body.onload = function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "sendWord"}, function(response) {
alert(response.word);
});
});
};
Let the your content.js file as is.
manifest.json
"browser_action": {
"default_icon": "images/W.png",
"default_popup": "popup.html",
"default_title": "Wordomania"
}
Hope this will solve your problem.

Chrome extension get DOM text and show it in popup.html on click on button

There are a ton of information about this on SO and elsewhere, but I couldn't get it to work!
I have this popup.html:
<html>
<head>
<title>My popup that should display the DOM</title>
<script src="popup.js"></script>
</head>
<body>
<button id="btn">Click!</button>
<input type="text" id="info">
</body>
</html>
my manifest.json:
{
"manifest_version": 2,
"name": "Get HTML example w/ popup",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": [ "http://*/*", "https://*/*" ],
"js": ["jquery-2.2.1.min.js","content.js"]
}],
"browser_action": {
"default_icon": "icon.png",
"default_title": "Get HTML example",
"default_popup": "popup.html"
},
"permissions": ["tabs"]
}
background.js:
function doStuffWithDOM(infoHtmlText) {
alert("I received the following DOM content:\n" + infoHtmlText);
chrome.extension.getBackgroundPage().info = infoHtmlText;
}
chrome.tabs.onUpdated.addListener(function(id,changeInfo,tab){
if(changeInfo.status=='complete'){ //To send message after the webpage has loaded
chrome.tabs.sendMessage(tab.id, { status: "ok" },function(response){
infoHtmlText = $("#domElement").text();
doStuffWithDOM(infoHtmlText);
});
}
})
content.js:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
/* If the received message has the expected format... */
if (msg.status && (msg.status == "ok")) {
/* Call the specified callback, passing
the web-pages DOM content as argument */
sendResponse("something?");
}
});
Is there a simple example, where you can click on a button in the popup and get content from the DOM and show it in the popup?
Here is a sample code based from your codes:
popup.js
function hello() {
var name = document.getElementById('info').value;
alert("Hello " +name);
}
document.getElementById('btn').addEventListener('click', hello);
popup.html
<html>
<head>
<title>My popup that should display the DOM</title>
</head>
<body>
<button id="btn">Click!</button>
<input type="text" id="info">
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
manifest.json
{
"manifest_version": 2,
"name": "Get HTML example w/ popup",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_icon": "icon.png",
"default_title": "Get HTML example",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}
background.js : leave blank (not sure on this on because I'm new at chrome development) but it is working.
I got the answer from this SO question, if you directly use inline headers you will encounter this error message:
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

I don't understand Google Chrome extensions. Please help.

I want to do something that seems like it should be fairly simple, but I can't get it to work.
All I want it to do is when the button in the popup is clicked I want to log the word "Hello" to the console. At the moment nothing happens. No error message. Just nothing.
Here is my manifest.jason file
{
"name": "Content Script",
"version": "1.0",
"description": "Experiments with content scripts.",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html"
}
}
Here is my popup.html
<h1>Hello</h1>
<script>
function changeField() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {"code": "sayHello"});
});
}
</script>
<button onclick="changeField();">Click</button>
Here is my contentscript.js
function sayHello() {
console.log("Hello");
}
chrome.extension.onRequest.addListener(
function(request, sender, response) {
if(request.code == 'sayHello') {
sayHello();
}
}
);
I've been reading the docs but they seem to skip over a lot of things. If someone could explain why this doesn't work I would be eternally grateful.
You didn't inject your content script to the page which console lives in.
Add content_scripts segment to your manifest.json file.
There is a reference of manifest.json file on chrome extension official site.
{
"name": "Content Script",
"version": "1.0",
"description": "Experiments with content scripts.",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"browser_action": {
"popup": "popup.html"
},
"content_scripts":[{
"matches":["http://*/*"],
"js":["content_script.js"]
}]
}

Categories