Get button clicked with chrome extension - javascript

I want to know how to detect if a button with a certain id is clicked on a webpage with my chrome extension.
With my code I have an error saying that my element is undefined.
Here is my manifest :
{
"manifest_version": 2,
"name": "app",
"description": "my app",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Changer le background"
},
"permissions": [
"activeTab",
"storage"
]
}
And my popup.js file :
document.addEventListener('DOMContentLoaded', () => {
getCurrentTabUrl((url) => {
document.getElementById('mybutton').addEventListener('click', function() {
var script = "console.log('clicked');";
chrome.tabs.executeScript({code: script});
});
});
});

your popup.js will not load until the user himself will click on the extension's icon... i think you should change your approach and use a content-script like this:
document.getElementById('mybutton').addEventListener('click', function() {
console.log('clicked');
});
you'll need to update your manifest.json for using a content script, something like that:
"content_scripts": [
{
"matches": ["the url of a page for the script", "the url of another page"],
"js": ["your_script.js"]
}
],

Related

chrome extension changing icon not working as expected

manifest.json
{
"manifest_version": 2,
"name": "Project",
"description": "Chrome Extension for sending messages",
"version": "1.0",
"browser_action": {
"default_icon": "red_dot.png"
},
"permissions": [
"activeTab",
"https://ajax.googleapis.com/",
"storage"
],
"background" : {
"scripts" : ["background.js"]
},
"content_scripts": [
{
"matches":["https://www.website.com/*"],
"js":["keypress.js", "jquery.js", "js_file.js"],
"run_at": "document_end"
}
]
}
background.js
var running = false
chrome.browserAction.onClicked.addListener(function(tab) {
if (running) {
alert('script is running, turning off');
chrome.browserAction.setIcon({path: "red_dot.png"})
running = false
} else {
alert('script is not running, turning on');
chrome.browserAction.setIcon({path: "green_dot.jpg"})
running = true
}
});
When I click on the icon, I get the popup as expected, but the icon itself isn't changing.
I'm getting this error:
Unchecked runtime.lastError: Icon invalid.
but I don't understand why. The code seems valid.
use this api and carefully enter params specifically path
https://developer.chrome.com/extensions/browserAction#method-setIcon

Chrome Extension : Append button on a page and execute script after clicking on appended element

I am working on a chrome extension that will enable user to click on an added button to inform me of their interest.
Basically, I built a chrome extension which displays a toolbar and I want the user to be able to click on this toolbar and execute a script after it.
Here are my codes and it does not work...
manifest.json file :
{
"manifest_version": 2,
"name": "XX Extension",
"version": "1.0",
"description": "The best extension for my friends",
"icons":{
"128" : "images/icon128.png",
"48" : "images/icon48.png",
"16" : "images/icon16.png"
},
"background": {
"scripts": ["js/jquery-3.4.1.min.js", "js/background.js"]
},
"permissions": [
"contextMenus",
"activeTab",
"tabs",
"notifications"
],
"content_scripts": [
{
"matches": ["https://www.mysite.fr/produit/*", "*://*.mysite.fr/produit/*"],
"css": ["css/extension_style.css"],
"js": ["js/jquery-3.4.1.min.js", "js/content.js"]
}
],
"browser_action": {
"default_icon": "images/icon16.png",
"default_title": "XX Extension",
"default_popup": "popup.html"
},
"web_accessible_resources": [
"toolbar.html",
"css/extension_style.css"
]
}
content.js file :
var script_text=$("script:contains(['ean'])").html();
var product_ean=script_text.split("['product']['ean']")[1].split(";")[0].replace("= '","").replace("'","");
chrome.runtime.sendMessage(product_ean);
var url = chrome.extension.getURL('toolbar.html');
var height= '35px';
var iframe = "<iframe src='"+url+"' id='myOwnCustomToolBar_TT91' style='height:"+height+"'></iframe>";
$('html').append(iframe);
$('body').css('transform','translateY('+height+')');
/* Topbar clicked */
$('#myOwnCustomToolBar_TT91').on('click', function(){
alert('it is clicked');
// do stuff executing js script
});
background.js file :
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
alert("Le code EAN de ce produit RDC est "+response);
});
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.executeScript(null, {
code : "alert('Wow it is working guy');"
});
});
The chrome extension work well to alert the EAN code of the product but the click event on the appended topbar by the extension does not work...
Thank you very much for your feedback and help !
Best regards,

Chrome extension on a React page

I have a simple chrome extension that auto-fills the form on a page with default values.
manifest.json file
{
"manifest_version": 2,
"name": "Form Filler",
"description": "This extension auto fills form in a specific page.",
"version": "1.0",
"icons": {
"128": "128x128.png"
},
"page_action": {
"default_icon": "19x19.png",
"default_popup": "popup.html",
"default_title": "Form Filler"
},
"options_page":"options.html",
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
"content_scripts":[
{
"matches": ["http://test-site.com/*"],
"js": ["content.js", "jquery-3.1.0.min.js"]
}
],
"permissions": [
"tabs",
"storage",
"http://test-site.com/*"
]
}
and this is content.js file
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if (request.act == "fill"){
let name = request.name;
let email = request.email;
$('#name').val(name);
$('#email').val(email);
}
});
That works perfectly fine on a normal HTML page.
But it doesn't work on a react page.
I guess obvious reason is that things are handled by state and if I can somehow alter the state, I should be able to get it working.
I tried this code ( file = content.js )but no success
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.act == "fill") {
this.setState({"form.name": "My Name"});
}
}.bind(this));
This is the eventPage.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if (request.todo == "showPageAction")
{
chrome.tabs.query({active:true,currentWindow: true}, function(tabs){
chrome.pageAction.show(tabs[0].id);
});
}
});
I am unable to access the state in the extension JS.
What would be the proper way to perform this task?

How To Initiate A Message Request From Content Script On Tab Change?

I've an extension which need to keenly keep an eye on the URL of the very active tab in the browser [chrome]. Currently, I've been able to track those URL's which user load/reload from start. But if there is a tab change, the content script doesn't send message to background script and get back anything.
In fact I want to reload content.js script on tab change of user as well.
Here's what I've done till now:
CONTENT.JS:
// Code here....
chrome.extension.sendMessage({ wants: 'URL' }, function(res) {
var urlResponse = res.url;
});
// Code here....
Works pretty well, but this content.js doesn't fire on tab change. Instead it fires when a document is changed in same tab (like visiting new link, etc)
BACKGROUND.JS:
chrome.extension.onMessage.addListener(
function(script, sender, sendResponse) {
if (script.wants == 'URL') {
sendResponse({ maskedURL: sender.tab.url });
}
}
);
MANIFEST.JSON:
{
"manifest_version": 2,
"name": "NAME HERE",
"description": "DESC HERE",
"version": "1.1",
"options_page": "options.html",
"browser_action": {
"default_title": "NAME",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"icons": { "16": "icon.png",
"48": "icon.png",
"128": "icon.png" },
"permissions": [
"storage",
"<all_urls>",
"tabs"
],
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["content.js"]
}
],
"web_accessible_resources": [
"bg.png",
"*.woff",
"*.woff2"
],
"background": {
"scripts": ["background.js"]
}
}
Thank you!
EDIT: Xan please have a look:
Could not understand your question properly but I will try to clarify to the best of my knowledge.
content.js is run once when a new page is opened or an existing page is refreshed.It cant access the details of the currently active tab.
If you want to know about any details of the tabs,use chrome.tabs API in background.js
chrome.tabs.onActivated.addListener(activeInfo){ //Fired when an active tab is changed
chrome.tabs.query({'active':true,'currentWindow':true},function(array_of_tabs){//Gives details of the active tab in the current window.
alert(array_of_tabs[0].url);
});

How to insert HTML with a chrome extension?

I have a context menu option and when it is selected I want insert some HTML. I have tried doing this
var div=document.createElement("div");
document.body.appendChild(div);
div.innerText='test123';
But it's not working for me.
Note I am trying to avoid using jQuery.
Here you can research how to create an extension and download the sample manifest.json.
Content Scripts can be used to run js/css matching certain urls.
manifest.json
{
"name": "Append Test Text",
"description": "Add test123 to body",
"version": "1.0",
"permissions": [
"activeTab"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["content-script.js"]
}
],
"browser_action": {
"default_title": "Append Test Text"
},
"manifest_version": 2
}
content-script.js
var div=document.createElement("div");
document.body.appendChild(div);
div.innerText="test123";
The above will execute the content-script.js for all urls matching http://*/* where * is a wildcard. so basically all http pages.
Content scripts have many properties which can be found in the link above.
Programmatic injection can be used when js/css shouldn't be injected into every page that matches the pattern.
Below shows how to execute the js onclick of the extension icon:-
manifest.json
{
"name": "Append Test Text",
"description": "Add test123 to body",
"version": "1.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Append Test Text"
},
"manifest_version": 1
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
code: 'var div=document.createElement("div"); document.body.appendChild(div); div.innerText="test123";'
});
});
This uses the executeScript method, which also has an option to call a separate file like so:-
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
file: "insert.js"
});
});
insert.js
var div=document.createElement("div");
document.body.appendChild(div);
div.innerText="test123";

Categories

Resources