I'm trying to use a variable I created in content.js in my background.js file.
Currently, when I try to use a variable in my background.js that was created in my content.js, I get a chrome error saying "Unexpected Identifier" (referencing ContentTag1 in background.js)
Do you know how I can do this?
Code from my Background.js File
function appendData(data) {
var mainContainer = document.getElementById("myData");
for (var i = 0; i < data.length; i++) {
if data[i].DBTag == ContentTag1 {
var div = document.createElement("div");
div.innerHTML = 'Name: ' + data[i].Name + ' ' + data[i].Price;
mainContainer.appendChild(div);
}
}
}
Code from my Content Script
var ContentTag1 = "test";
var ContentTag2 = "test";
var ContentTag3 = "test";
Manifest Below:
{
"name": "App",
"version": "1.0",
"description": "Description",
"permissions": [ "activeTab", "declarativeContent", "storage", "http://localhost:3000/brands"],
"background": {
"scripts": [ "js/lib/jquery.min.js", "js/app/background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [ "https:/somesite*" ],
"css": ["style.css"],
"js": [
"js/lib/jquery.min.js",
"js/app/content.js"
],
"all_frames": false
}
],
"web_accessible_resources": ["content.html",
"content.css",
"css/popup.css"
],
"browser_action": {
"default_popup": "views/popup.html",
"default_icon": {
"16": "images/someimage.png",
"32": "images/someimage.png",
"48": "images/someimage.png",
"128": "images/someimage.png"
}
},
"icons": {
"16": "images/someimage.png",
"32": "images/someimage.png",
"48": "images/someimage.png",
"128": "images/someimage.png"
},
"manifest_version": 2
}
You should send a message from content and add a listener on background
here an answer that show example of that.
Also you may find here the documentation about messaging in chrome extention.
Related
I need to find the id of the element that holds text that I've selected, and I've been unsuccessful at finding a way to do this. It looks like the problem is with the fact that you can't use a getAttribute method on a window object. I am using a content script that communicates with an event page to carry it out. This is my content script:
let element = window.getSelection().anchorNode;
let finder = element.getAttribute('id');
alert(finder.toString()); //test
This is my event page:
chrome.contextMenus.create({ id: "M", title: "Feature One", contexts: ["selection"] });
chrome.contextMenus.create({ id: "ATCB", title: "Feature Two", contexts: ["selection"] });
chrome.contextMenus.onClicked.addListener(function(clickData){
if (clickData.menuItemId == "M" && clickData.selectionText){
//var one = clickData.selectionText;
chrome.tabs.executeScript({
file: 'contentScript.js'
});
}
if (clickData.menuItemId == "ATCB" && clickData.selectionText){
var two = clickData.selectionText;
alert(two + " two"); //test
}
});
And this is my manifest file:
{
"manifest_version": 2,
"name": "Menu",
"version": "1.0",
"icons": {
"128": "icon.png",
"48": "icon.png",
"16": "icon.png"
},
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}],
"permissions": [
"contextMenus",
"tabs",
"activeTab",
"file://*/*",
"https://*/*",
"http://*/*"
]
}
Thank you for reading my question
This can be accomplished with document.activeElement.id;
https://www.w3schools.com/jsref/prop_document_activeelement.asp
I'm building a Chrome Extension that expands all collapsed text on a a web page.
Heres a snippet of the code:
manifest.json
{
"manifest_version": 2,
"name": "filterq2",
"version": "1.0",
"icons": {
"128": "icon_16.png"
},
"browser_action": {
"default_title": "Preguntas"
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [{
"matches": ["https://www.quora.com/*"],
"js": ["contentScript.js"],
"run_at": "document_end"
}],
"permissions": [
"https://*/*",
"http://*/*",
"tabs"
]
}
contentScript.js
function eventFire(el, etype) {
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
var losExpandibles = document.getElementsByClassName("ui_qtext_more_link");
for (var i = 0; i < losExpandibles.length; i++) {
eventFire(losExpandibles[i], 'click');
}
I try to simulate a left click of the mouse on every element with class name: "ui_qtext_more_link" but the for loop breaks after first pass.
But if I run it in the console it works on every element just fine. What am I missing?
I want to be able to add a global CSS when I click browserAction & remove the same global css when I click browserAction again.
These are my file contents.
background.js
import browser from 'webextension-polyfill'
let hasInserted = false
const css = `* {font-family: redactedregular !important;}`
browser.browserAction.onClicked.addListener(function(tab) {
if (!hasInserted) browser.tabs.insertCSS(tab.id, { code: css })
else browser.tabs.removeCSS(tab.id, { code: css })
hasInserted = !hasInserted
})
manifest.json
{
"manifest_version": 2,
"name": "Redact The Web",
"offline_enabled": true,
"version": "1.0.0",
"description": "Extension that redacts text on the web",
"icons": {
"16": "icon16.png",
"19": "icon19.png",
"24": "icon24.png",
"32": "icon32.png",
"38": "icon38.png",
"48": "icon48.png",
"64": "icon64.png",
"128": "icon128.png"
},
"background": {
"scripts": ["background.js"]
},
"browser_action": {},
"permissions": ["activeTab", "https://*/*", "http://*/*"]
}
The thing is CSS gets inserted but it doesn't get removed if I click again. How do I solve it?
This is technically not the answer since it's an open issue on bugs.chromium.org but I managed to make my code work using another technique #wOxxOm told above in the comments.
I inserted CSS as a link & removed it. Here's the Gist:
background.js
import browser from 'webextension-polyfill'
let hasInserted = false
browser.browserAction.onClicked.addListener(function(tab) {
browser.tabs.executeScript({ file: 'content.js' })
if (!hasInserted) {
browser.tabs.sendMessage(tab.id, {
command: 'insertCSS',
})
} else {
browser.tabs.sendMessage(tab.id, {
command: 'removeCSS',
})
}
hasInserted = !hasInserted
})
content.js
import browser from 'webextension-polyfill'
function insertCSS(file) {
const style = document.createElement('link')
style.rel = 'stylesheet'
style.type = 'text/css'
style.href = browser.extension.getURL('style.css')
style.id = file
document.getElementsByTagName('html')[0].appendChild(style)
}
function removeCSS(file) {
const cssNode = document.getElementById(file)
cssNode && cssNode.parentNode.removeChild(cssNode)
}
browser.runtime.onMessage.addListener(message => {
const id = 'redact-the-web'
if (message.command === 'insertCSS') {
insertCSS(id)
} else if (message.command === 'removeCSS') {
removeCSS(id)
}
})
manifest.json
{
"manifest_version": 2,
"name": "Redact The Web",
"offline_enabled": true,
"version": "1.0.0",
"description": "Extension that redacts text on the web",
"icons": {
"16": "icon16.png",
"19": "icon19.png",
"24": "icon24.png",
"32": "icon32.png",
"38": "icon38.png",
"48": "icon48.png",
"64": "icon64.png",
"128": "icon128.png"
},
"background": {
"scripts": ["background.js"]
},
"browser_action": {},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_start"
}
],
"web_accessible_resources": ["style.css"],
"permissions": ["https://*/*", "http://*/*"]
}
I open-sourced the whole code on GitHub → https://github.com/deadcoder0904/redact-the-web
In chrome documentation, we can send message from option page by using:
chrome.runtime.sendMessage
We cannot use:
chrome.tabs.sendMessage
I want to send message from option page to content script. Can I do it directly?
This is my option page script:
document.addEventListener("DOMContentLoaded", function() {
var radio = document.querySelectorAll("input[type=radio][name=quality]");
for(i=0; i<radio.length; i++)
radio[i].addEventListener("change", function(){
val = this.id;
localStorage.setItem("youtube_filter_video_quality", val);
chrome.runtime.sendMessage({"youtube_filter_video_quality": val});
});
});
And here is content script:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.youtube_filter_video_quality!==undefined){
console.log(request.youtube_filter_video_quality);
}
}
);
And here is manifest.json:
{
"name": "__MSG_name__",
"short_name": "__MSG_short_name__",
"manifest_version": 2,
"version":"1.5.0.0",
"description": "__MSG_description__",
"default_locale": "en",
"browser_action": {
"default_icon": "48.png",
"default_title": "__MSG_default_title__",
"default_popup": "popup.html"
},
"background":{
"page":"background.html",
"persistent": false
},
"content_scripts":[
{
"matches": [ "*://*.youtube.com/*" ],
"css": ["app_player.css"],
"run_at": "document_end"
}
],
"permissions": [
"tabs",
"activeTab",
"storage",
"<all_urls>",
"webNavigation"
],
"icons": {
"64":"64.png",
"48": "48.png",
"32":"32.png",
"16": "16.png",
"128": "128.png"
},
"options_page": "options.html",
"options_ui": {
"chrome_style": true,
"page": "option.html"
}
}
The console.log cannot write anything (blank).
I'm new to chrome extensions and cannot seem to figure out how the background concept works. I am building a counter extension that keeps counting even when the user closes the extension (but not the browser) and wanted to do a simple test to see if I could figure out how to use the background file. Below is my attempt to create a function that activates everytime a user clicks on a tab (outside of my extension) and when they click on 5 tabs, the alert hits. I cannot figure out why this doesn't work.
background.js:
var counter = 0;
chrome.browserAction.onClicked.addListener(function(tab){
counter++;
if (counter == 5) {
alert("Hi");
}
});
manifest.json:
{
"name": "Hello World!",
"description": "My first packaged app.",
"version": "0.1",
"permissions": ["tabs", "http://*/*"],
"manifest_version":2,
"content_scripts": [ {
"js": [ "jquery-1.9.1.js", "myscript.js" ],
"matches": [ "http://*/*", "https://*/*"]
}],
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"default_title": "10,000 Hours",
"default_icon": "icon16.png",
"default_popup": "index.html"
},
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
}
It is working for me with following code.
manifest.json
{
"name": "Popping Alert",
"description": "http://stackoverflow.com/questions/15194198/background-js-not-working-chrome-extension",
"background": {
"scripts": [
"background.js"
]
},
"version": "1",
"manifest_version": 2,
"browser_action": {
"default_title": "Click Me"
}
}
background.js
var counter = 0;
chrome.browserAction.onClicked.addListener(function (tab) {
counter++;
if (counter == 5) {
alert("Hey !!! You have clicked five times");
}
});
Can you share your related code or put your problem statement clearly if this does not work?