Chrome extension - how to pass the values to background page - javascript

I have a small assignment.I need help on that..i am new to this stackoverflow..
The problem is of my extension..i have tried many methods in various tutorials and articles..
i need to achieve this.
I have an extension and when i click on it ,it should capture the current url of the page and open a new tab with the url and the source code (html structure) of the page..both the sourcecode and url must be stored somewhere .. like in an object or something..
So far i have done this.
manifest.json
{
"name": "ncubicx",
"version": "0.0.1",
"manifest_version": 2,
"browser_action": {
"default_icon": {
"19": "img/19x19.png",
"38": "img/38x38.png"
},
"default_title": "That's the tool tip"
},
"permissions": [
"activeTab",
"tabs",
"cookies",
"contextMenus",
"<all_urls>"
],
"background": {
"scripts": ["background.js"],
"persistent": true
}
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
});
chrome.tabs.create({url: 'newtab.html'}) ;
});
I dont know how to display the url in newtab.html or how to store the url's somewhere.
Hope someone helps me in this..
Thanks in advance..

You can capture the url of tab from background page and html source code from content script. Once you have both, open a new tab and send the object to this new tab where you can populate the html by yourself.
Note : Before sending the object to new tab, you need to wait for tab to load. So i have added a check for that.
Here's the whole code:
manifest.json:
{
"name": "Demo",
"version": "0.0.1",
"manifest_version": 2,
"description": "practice",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"default_locale": "en",
"background": {
"scripts": [
"src/bg/background.js"
],
"persistent": true
},
"browser_action": {
"default_icon": "icons/icon19.png",
"default_title": "browser action demo"
},
"permissions": [
"https://*/*","tabs"
],
"content_scripts": [
{
"matches": [
"https://*/*"
],
"js": [
"js/jquery/jquery.min.js",
"src/content/content.js"
]
}
]
}
background.js:
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.query({active: true,currentWindow: true}, function(tabs){
var url = tabs[0].url;
chrome.tabs.sendMessage(tabs[0].id, {message : "getHtml"},function(response){
var html = response.html;
var obj ={
tabUrl : url,
tabHtml : html
};
createNewtab(obj);
});
});
});
function createNewtab(obj){
var targetId = null;
chrome.tabs.onUpdated.addListener(function listener(tabId, changedProps) {
if (tabId != targetId || changedProps.status != "complete")
return;
chrome.runtime.sendMessage({message: "loadNewTab", data: obj});
});
var newTabUrl = chrome.extension.getURL('newTab.html');
chrome.tabs.create({ url: newTabUrl}, function(tab) {
targetId = tab.id;
});
}
content.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
switch (request.message){
case "getHtml":
var src = $("html").html();
sendResponse({html: src});
break;
}
});
newTab.html:
<html>
<head>
<script src="src/newTab.js"></script>
</head>
<body>
//You can populate data as you like
</body>
</html>
newTab.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
switch (request.message){
case "loadNewTab":
console.log(request.data);
//You have the object as request.data with tabUrl and tabHtml
break;
}
});

Related

How to start google extension on tab switch

I have made a simple extension that checks if a URL is on a list. If it is the extension icon changes color for 2 seconds.
I would like it to automatically switch the icon color on tab switch instead of me having to click the extension icon.
This is my current code :
var good_urls = \["https://www.google.com/%22,%22https://www.youtube.com"\];
var currentURL
chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
function(tabs){
getCurrentURL(tabs\[0\].url);
updateIcon();
});
function getCurrentURL(tab){
currentURL = tab;
console.log(currentURL);
}
function updateIcon(){
if(good_urls.indexOf(currentURL) >= 0) {
console.log("good");
chrome.action.setIcon({path: "icon-on-list.png"});
console.log("1")
setTimeout(() => { chrome.action.setIcon({path: "neutral.png"}); }, 1000);
}
else {
chrome.action.setIcon({path: "icon.png"});
console.log("3")
setTimeout(() => { chrome.action.setIcon({path: "neutral.png"}); }, 1000);
};
}
+HTML that activates the script
<html>
<head>
</head>
<body>
<script src="background.js"></script>
</body>
</html>
+Manifest
{
"manifest_version": 3,
"name": "Icon Changer",
"version": "1.0",
"background": {
"service_worker": "background.js"
},
"permissions": [
"tabs",
"activeTab",
"declarativeContent",
"storage"
],
"action": {
"default_icon": "neutral.png",
"default_popup": "popup.html"
}
}
I have no clue how to make the script start automatically.
I am sure its super simple, I am new to making chrome extensions. Thank you for your help.
This is a sample of chrome.tabs.onActivated.
manifest.json
{
"name": "hoge",
"version": "1.0",
"manifest_version": 3,
"permissions": [
"tabs"
],
"background": {
"service_worker": "background.js"
}
}
background.js
console.log("background.js");
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
console.log(tab.url);
});
});

Chrome Extension Content-Script as Listener & Popup as Sender, But Gives Receiving End Does Not Exist

Answer Found
This extension is for google meet. What I have written in manifest.json is wrong, line "matches": ["*://*.meet.google.com/*"], should be "matches": ["*://meet.google.com/*"],
Original Question
I have this chrome extension, I want to let my contentScript.js to search for an element (tag) in a webpage when I press a button in popup.html. I set the sending message part in popup.js and the sending seems to work fine. But when I tried to receive it on the contentScript.js, console.log gives me Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
May someone please help me, any suggestions are welcome.
Code snippets:
popup.js
retrieveTabId();
function retrieveTabId() {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
var activeTab = tabs[0];
console.log("tabID", activeTab.id);
tabId = activeTab.id;
});
}
document.getElementById("btn").addEventListener('click', function (){
chrome.tabs.sendMessage(tabId, {type: "listener"}, function(response) {
console.log((response.success));
});
console.log("tabID", tabId);
})
content-script.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.type == 'listener') {
try {
let textarea = document.getElementsByTagName('textarea');
if (textarea.length == 0) {
sendResponse({success: false});
}
else {
console.log('find node -- textarea' + textarea);
sendResponse({success: true});
}
}
catch (e){
console.log(e);
sendResponse({success: false});
}
}
}
);
manifest.json
{
"name": "name",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"permissions": ["storage", "activeTab", "scripting", "downloads", "notifications", "<all_urls>", "tabs"],
"action": {
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [{
"matches": ["*://*.meet.google.com/*"],
"js": ["contentScript.js"]
}]
}

Chrome Extension: why I can't pass variable to function (JS)

I am new at JavaScript.
I am working on Chrome Extension now.
I need to parse project name from page (Vtiger CRM), then create Card in Trello, name of the card must be the parsed project name. (sorry for my English).
manifest.json
{
"manifest_version": 2,
"name": "Roonyx VTIGER optimizer",
"version": "0.0.1",
"description": "Создание доски в Trello и чата в Discord",
"icons": {
"64": "icon.png"
},
"browser_action": {
"default_icon": "icon.png",
"default_title": "Roonyx VTIGER optimizer",
"default_popup": "popup.html"
},
"web_accessible_resources": [
"settings/index.html",
"popup.html"
],
"options_page": "settings/index.html",
"content_scripts": [
{
"js": [
"scripts/jquery-2.1.1.js",
"scripts/client.js",
"scripts/key.js",
"scripts/settings.js",
"scripts/hashSearch.js"
],
"run_at": "document_idle",
"matches": [ "<all_urls>" ]
}
],
"background": {
"scripts": ["scripts/background.js"],
"persistent": false
},
"permissions": ["storage", "identity", "tabs", "<all_urls>"]
}
Here is part of my background.js code:
var myProject;
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
window.myProject = $(request.content).find(".projectname").text();
});
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.executeScript(tab.id, {
code: "chrome.extension.sendMessage({content: document.body.innerHTML}, function(response) { console.log('success'); });"
}, function() { console.log('done'); });
});
// Trello Creating Card
var APP_KEY = '*app_key*';
var myList = '5d1089c67893fe7afb014694';
function trelloInit() {
Trello.setKey(APP_KEY);
Trello.setToken(localStorage.getItem('trello_token'));
}
var creationSuccess = function (data) {
console.log('Card created successfully.');
console.log(JSON.stringify(data, null, 2));
console.log(myProject);
};
var newCard = {
name: myProject,
desc: 'This is the description of our new card.',
// Place this card at the top of our list
idList: myList,
pos: 'top'
};
function createCard() {
$("#trello_create_card").click(function () {
trelloInit();
Trello.post('/cards/', newCard, creationSuccess);
});
}
$(document).ready(createCard);
I see needed project name in console as expected, when script executes "console.log(myProject)" in creationSuccess function.
But I see created card with blank name in Trello.
I have already tried to use window.myProject in newCard, but nothing changes...
If you need to see the entire setup, you can see repo at GitHub:
https://github.com/AnatolySt/chrome-roonyx
Could anybody explain what I'm doing wrong please?
Thank you in advance)

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.

Send the active tab info from background.js to the pop-up (window)

I am trying to send the currrent active tab information to a pop-up page from the background script but am getting "undefined" when doing so.
Background script:
//load popup.html in a pop-up window.
chrome.browserAction.onClicked.addListener(function() {
chrome.windows.create({'url': 'HTML/popup.html', 'type': 'popup'},
function(window) {
});
});
//return current active tab
function backgroundFunction () {
var tab = "";
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
tab = tabs[0].title;
});
return tab;
}
popup.js:
(function () {
var otherWindows = chrome.extension.getBackgroundPage();
console.log(otherWindows.backgroundFunction());
})();
My Manifest file:
{
"manifest_version": 2,
"name": "Application Test",
"version": "1.0",
"description": "Test Application",
"icons": {
"128": "icons/icon128.png",
"48": "icons/icon48.png",
"16": "icons/icon16.png"
},
"browser_action":{
"default_icon": "icons/icon16.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"<all_urls>",
"activeTab"
]
}
I suspect it is undefined because the background script tab is now "undefined" because of the pop-up window.
How can I sucessfully send the tab info for whatever URL the user was on to the popup.js file when they click the Extension icon?
Use chrome.runtime, most methods are deprecated in chrome.extension
chrome.runtime.getBackgroundPage(backgroundWindow => {
console.log(backgroundWindow.backgroundFunction());
});

Categories