Map data in contentscript.js to chartjs in chrome extension - javascript

I'm building a chrome extension that displays data from an API in a chart. I've been able to get the data from each endpoint successfully. The chart library used is chartjs. I have been able to send data from background.js to contentScript.js. The challenge I'm currently facing is hooking the data to chartjs in the contentscript.js in the extension. Below is the code.
Background.js
const data = {
data1: data1,
data2: data2,
data3: data3
};
console.log("data", data);
// wait for tab to fully load
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == "complete") {
// sendMessage
chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0]?.id, { data: data }, (response) => {
console.log(response);
});
});
}
});
ContentScript.js
chrome.runtime.onMessage.addListener((sender, sendResponse, message) => {
console.log(message)
console.log(sender)
sendResponse("received")
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ["Message1", "Messages", "Message3"],
datasets: [
{
label: "User Info",
backgroundColor: ["#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"],
data: [sender.data1, sender.data2,sender.data3]
},
]
},
options: {
legend: { display: true },
title: {
display: true,
text: 'Your Metrics'
}
}
});
})
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data</title>
<script src="./chart.min.js"></script>
</head>
<body>
<div>
<h2>Data Analytics</h2>
<hr>
<div style="width: 30rem; height:20rem;display:flex;">
<canvas id="bar-chart"></canvas>
</div>
</div>
<script src="./contentScript.js"></script>
</body>
</html>
manifest.json
{
"manifest_version": 3,
"name": "Data Fetch",
"version": "0.1.0",
"description": "Get data from api",
"permissions": ["tabs", "cookies", "storage","activeTab"],
"host_permissions": ["https://*.site.com/*"],
"background": {
"service_worker": "./background.js"
},
"content_scripts": [
{
"matches": ["https://*.site.com/*"],
"js": ["contentScript.js", "chart.min.js"]
}
],
"action": {
"default_popup": "index.html",
"default_title": "Data Stats",
"default_icon": "images/data-icon.png"
}
}

Related

Javascript: Browser Extension navigate.clipboard.write() not working in content.js

In my extension I have a button in a popup.js file that runs a listener for a button press and sends a command to a content.js file.
document.querySelector('#btn').addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) =>
chrome.tabs.sendMessage(tabs[0].id, { command: 'getClientName' })
);
});
My content.js file is a little involved and grabs some information off the page to copy to the clipbaord, but for purposes of my problem I just need a listener to wait for the command "getClientName" then save a value to the clipboard like below.
chrome.runtime.onMessage.addListener((msg, sender, response) => {
navigator.clipboard.writeText("I did it 2!")
.then(() => {alert("I did it 2!");
})
.catch(() => {
alert("I didn't it 2");
})
});
However, I cannot get navigator.clipboard.writeText() to work from the content.js page. It will only work if I run it directly from popup.js, which doesn't really work since I need to pull information off the page.
Right now it gets sent to .catch() and sends me the error message.
Manifest (replaced the actual URL in my manifest with "all" for privacy reasons):
{
"manifest_version": 3,
"name": "The Magic Button",
"version": "1.0.0",
"description": "Open P.P. client folder in sharepoint",
"action": {
"default_icon": {
"16": "/images/logo16.png",
"48": "/images/logo48.png",
"64": "/images/logo64.png",
"128": "/images/logo64.png"
},
"default_popup": "popup.html",
"default_title": "Open Sharepoint Folder"
},
"permissions": ["tabs",
"clipboardWrite"],
"content_scripts": [
{
"matches": [all],
"js": ["content.js"],
"css": ["/styles/contentStyle.css"],
"run_at": "document_idle",
"all_frames": false
}
]
}
This sample copies the web page title to the clipboard.
manifest.json
{
"name": "hoge",
"version": "1.0",
"manifest_version": 3,
"permissions": [
"scripting"
],
"host_permissions": [
"<all_urls>"
],
"action": {
"default_popup": "popup.html"
}
}
popup.html
<html>
<body>
<button id="copy">Copy</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
const getTitle = () => {
console.log("getTitle() = " + document.title);
return document.title;
}
document.getElementById("copy").onclick = () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
console.log("Execute Script");
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: getTitle
}, (result) => {
console.log("Recv result = " + result[0].result);
navigator.clipboard.writeText(result[0].result);
});
});
}

Can't get chrome extension to get innerText when loading

I am building my first chrome extension and want to read the entire text in the website whenever a new tab is loaded. Everything works with a button, but I can't trigger it automatically.
Here's what I have in my popup.js
let getWords = document.getElementById("getWords");
// When the button is clicked, inject getPageText into current page
getWords.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: getPageText,
});
});
chrome.tabs.onUpdated.addListener(function(tab) {
chrome.tabs.executeScript({
target: { tabId: tab.id },
func: getPageText,
});
});
// The body of this function will be executed as a content script inside the
// current page
function getPageText() {
let websiteWords = document.body.innerText;
console.log(websiteWords);
}
My popup.html
<html>
<head>
<link rel="stylesheet" href="assets/css/layout.css" />
<link rel="stylesheet" href="assets/css/ui.css" />
</head>
<body>
BODY
</body>
<button id="getWords">Words</button>
<script src="popup.js"></script>
</html>
on my background.js I tried this but it doesn't work:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(changeInfo.status === "complete"){
console.log("loaded....")
}
});
function getPageText() {
let websiteWords = document.body.innerText;
console.log(websiteWords);
}
Finally my manifest.json
"manifest_version": 3,
"permissions": [
"activeTab",
"webNavigation",
"storage",
"scripting"
],
"host_permissions": [
"https://*/*"
],
"background": {
"service_worker": "background.js",
"type": "module"
},
"action": {
"default_popup": "popup.html"
},
I think you should use content_scripts.
manifest.json
{
"name": "hoge",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"matches.js"
]
}
]
}
matches.js
function getPageText() {
let websiteWords = document.body.innerText;
console.log(websiteWords);
}
getPageText();

I want to do message passing from web page to chrome extension html but seems no response is coming. Here is the code

Below is the code m trying but getting response null in popup. I want to do message passing from web page to chrome extension html .
mainfest.json
{
"manifest_version": 2,
"name": "AnyName",
"description": "A simple extension for Chrome",
"version": "1.0",
"author": "#aag",
"background": {"scripts": ["background.js"]},
"permissions":[
"tabs", "http://*/*", "activeTab", "storage", "ftp://*/*", "<all_urls>", "clipboardWrite", "contentSettings", "cookies", "history"
],
"page_action": {
"default_icon": "logo.png" ,
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["*://*/show_bug.cgi?id/*"],
"js": ["content.js"],
"run_at": "document_start"
}]
}
popup.html
<!doctype html>
<html>
<head>
<title>Extension</title>
<script src="popup.js"></script>
<script src="jquery.js"></script>
</head>
<body>
<h3>Whiteboard!!</h1>
<p id='pagetitle'>Page is still Loading..</p>
<p id='reported'>Date is still Loading..</p>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function() {
prepareSummary();
});
function prepareSummary() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {
action: "getSummary"
}, function(response) {
if (response == null) {
alert('no respose');
} else {
var wbVar = response.wb;
var rdateVar = response.rd;
document.getElementById('pagetitle').innerHTML = wbVar;
document.getElementById('reported').innerHTML =rdateVar ;
}
});
});
}
content.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.action == "getSummary") {
var wbVar = document.getElementById('status_whiteboard').value;
var rdateVar = document.getElementsByClassName("bz_comment_time")[0].innerText;
sendResponse({
wb: wbVar,
rd: rdateVar,
resp: "Test"
});
} else
sendResponse({
resp: "Nothing"
});
});
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
var url = tab.url;
if (isUrl(url)) {
chrome.pageAction.show(tab.id);
}
});
function isUrl(url) {
if (url.includes('show_bug.cgi?id'))
return true;
else
return false;
}
The main issue is i am not able to get the string coming on webpage. After fetching from webpage i need to show on extension popup.html

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 Extenstion(Js file) To Php Data Sending

So I am very new to chrome extensions and what i am trying to get done with my first chrome extension is to send a url from chrome extension to a php file.
I have tried $.post method and also $.ajax but the isset function in php to check post data always fails.
Here is my code:
manifest.json
{
"manifest_version": 2,
"name": "First Chrome Extension",
"description": "Send Url On Click",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["jquery-2.1.4.min.js"]
}
],
"permissions": [
"activeTab",
"http://*/",
"https://*/"
]
}
POPUP.html
<html>
<head>
<title>First Chrome Extension</title>
<script src="popup.js"></script>
</head>
<body>
<form name="testform">
<input type='button' id='alertButton' value='Send URL'>
<div id="returnfromphp"></div>
</form>
<script src="jquery-2.1.4.min.js"></script>
</body>
</html>
POPUP.js
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('alertButton').addEventListener('click', ShowUrl);
});
function ShowUrl(){
chrome.tabs.getSelected(null, function(tab) {
myfunction(tab.url);
});
}
function myfunction(tablink) {
var urlretained = tablink;
alert(urlretained);
$.ajax({
type: "POST",
url: "myfile.php",
data: {myData:urlretained},
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
alert('Addition Failed');
}
});
}
myfile.php
<?php
if(isset($_POST['myData'])){
echo"Data Detected";
}else{
echo"Data Not Set";
}
?>

Categories