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

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)

Related

Can't use sendMessage in popup.js of browser extension

I created a js script that goes with my popup.html for a chrome browser extension I'm working on. It listens for a change in a slider value on the HTML and then sends a message to the content.js script with the new data. However, it seems I can't use sendMessage in this script. I'm using manifest v3.
Here's my js:
var slider = document.getElementById("slider");
let value = slider.value;
//function is called when the slider moves
changeSlider = function() {
value = slider.value;
update();
}
update = function() {
chrome.runtime.sendMessage({ message: "update", data: value });
}
Here's my manifest:
{
"manifest_version": 3,
"name": "e",
"version": "0.1",
"author": "e",
"homepage_url": "https://www.example.com",
"permissions": [
"contextMenus",
"activeTab",
"nativeMessaging"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["src/content.js"]
}],
"web_accessible_resources": [
{
"resources": ["src/*"],
"matches": ["<all_urls>"],
"use_dynamic_url": true
}],
"background": {
"service_worker": "src/background.js"
},
"action":
{
"default_popup": "src/popup.html",
"default_icon": "src/resources/icon.png"
},
"icons": {
"16": "src/resources/icon-16.png",
"32": "src/resources/icon-32.png",
"48": "src/resources/icon-48.png",
"128": "src/resources/icon-128.png"
}
}
And here's the console error I get whenever I adjust the slider:
additionally, my interpreter doesn't autofill chrome.runtime, so I assume something went wrong there. Help :D

Error on calling Javascript APIs within Firefox extension

I am currently building a web extension and in the stage of porting between browsers. On moving from Chrome to Firefox I am coming against an issue in using the runtime.sendMessage API that allows me to talk between the content and background scripts.
The message code in the content script:
browser.runtime.sendMessage('d089938d-ba63-4c40-98ab-b8515db1bbca', { greeting: "screenshot-please" }, function (response) {
localStorage.setItem("image", response.farewell);
});
var image = localStorage.getItem("image");
The Background script:
var img = saved-image;
browser.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if(request.greeting === "screenshot-please"){
sendResponse({
farewell: img
});
}
}
);
and the manifest:
{
"description": "...",
"manifest_version": 2,
"name": "...",
"permissions": [
"find",
"tabs",
"activeTab",
"<all_urls>"
],
"applications": {
"gecko": {
"id": "..."
}
},
"background": {
"scripts": ["/JavaScript/moz-initialPopup.js"]
},
"content_scripts": [
{
"all_frames": true,
"matches": ["*://127.0.0.1:3000/*"],
"js": ["Javascript/dataGrab.js"]
}
],
"icons": {
"48": "..."
},
"browser_action": {
"browser_style": true,
"default_title": "...",
"default_icon": {
"48": "..."
}
},
"version": "1.0"
}
When in chrome (replace all instances of *browser with *chrome) this messaging system works fine. When in firefox, in the developer tools I get 'ReferenceError: browser is not defined'.
Can anyone assist me in why I would not be able to access the browser here?

Google Chrome - passing a variable to an extension

Currently I'm trying to pass an array from the context_script into my popup.html on a button click from the extension. However there have been complications which I can't seem to solve on my own, almost every single one of the implementation methods in SO and other sites don't seem to work out.
All I really need is to simply pass a single list from the context, into the JavaScript page that handles the extensions HTML interface.
background.js
"use strict";
function Master() {
firebase.initializeApp(config);
this.time = 0;
this.http_usage = this.get_http();
this.https_usage = this.get_https();
this.todays_usage = this.get_today_sites();
chrome.runtime.onMessage.addListener(function(message,sender,sendResponce) {
sendResponce("Hello world");
});
this.init();
}
manifest.json
{
"name": "Statistics",
"description": "Saves time and visitation data.",
"version": "1.0",
"manifest_version": 2,
"permissions": [
"activeTab",
"tabs",
"http://*/*",
"https://*/*",
"clipboardRead",
"clipboardWrite",
"background"
],
"content_scripts": [
{
"matches": [
"*://*/*"
],
"js": [
"config.js",
"firebase.js",
"background.js"
],
"css": [
"styles.css"
]
}
],
"browser_action": {
"default_title": "Statistics",
"default_popup": "popup.html"
}
}
popup.js
function get_data(){
let data = []
chrome.runtime.sendMessage({data:"giblist"}, function (responce) {
console.log(responce);
...
});
}
document.addEventListener('DOMContentLoaded', function () {
console.log("Loaded page");
firebase.initializeApp(config);
document.getElementById("showStatistics").addEventListener("click", get_data);
});

Chrome extension - how to pass the values to background page

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;
}
});

Chrome Extension: How do I get me Content Script Extension to show up on select websites

I would like my Chrome Extension to on show up on google and amazon. My manifest.json looks like this:
{
"background": {"scripts": ["background.js"]},
"content_scripts": [
{
"matches": ["*://*.google.com/*", "http://www.amazon.com/*", "*://*.amazon.com/*"],
"js": ["background.js"]
}
],
"name": "Denver Public Library Lookup",
"description": "Does Stuff",
"homepage_url": "http://www.artifacting.com",
"icons": {
"16": "icon-16.png",
"48": "icon-48.png",
"128": "icon-128.png" },
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"version": "1.0",
"manifest_version": 2
}
But it doesn't show up on either google or amazon and I can't figure out why.
Here is my background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {file: "bookmarklet.js"})
});
And here is the bookmarlet.js
setTimeout('x99.focus()', 300);
var re = /([\/-]|at[at]n=)/i;
if (re.test(location.href) == true) {
var isbn = RegExp.$2;
var x99 = window.open('http://searchsite/search/searchresults.aspx?ctx=1.1033.0.0.6&type=Keyword&term=' + atatn, 'Library', 'scrollbars=1,resizable=1,top=0,left=0,location=1,width=800,height=600');
x99.focus();
}
Any ideas? Thanks for your help.
Many mistakes in the code.
You don't need content script here, all operations could be executed
within background page content
It it hard to make background page
code works within content script, this is definitely not a your case.
So using the same background.js as both background and content script
does not work in your case at least
Manifest does not declare browser
action.
And so on
I strongly suggest to start with Google extension documentation. You will save a lot of your time.
How I think files might look like
manifest.json
{
"background": {"scripts": ["background.js"]},
"name": "Denver Public Library Lookup",
"description": "Does Stuff",
"homepage_url": "http://www.artifacting.com",
"icons": {
"16": "icon-16.png",
"48": "icon-48.png",
"128": "icon-128.png" },
"browser_action": {
"default_icon": {
"19": "images/icon-19.png",
"38": "images/icon-38.png"
},
"default_title": "Do Staff" // optional; shown in tooltip
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"version": "1.0",
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
// You need more sothisticated regexp here which checks for amazon and google domains
var re = /([\/-]|at[at]n=)/i;
if (re.test(tab.url)) {
var isbn = RegExp.$2;
var url = "http://searchsite/search/searchresults.aspx?ctx=1.1033.0.0.6&type=Keyword&term=" + isbn;
chrome.windows.create({
url : url,
left: 0,
top: 0,
width: 800,
height: 600,
focused: true,
type: "popup"
});
}
});
bookmarlet.js is not needed

Categories