Communication of background with content script - javascript

Im trying to communicate background with content script, but my way doesnt work. And I want to know why it doesnt work and how to solve this problem(other solutions dont work. idk why).
Manifest.json:
{
"manifest_version": 2,
"name": "X",
"version": "2.0",
"browser_action": {
"default_title": "title"
},
"permissions": [
"activeTab",
"tabs"
],
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["content_scripts/jquery.min.js", "content_scripts/script.js"],
"run_at": "document_idle"
}
],
"background": {
"scripts": ["background/background.js"]
},
"icons": {
"16": "icon.png",
"32": "icon.png",
"48": "icon.png",
"64": "icon.png",
"128": "icon.png"
}
}
Background.js:
chrome.tabs.query({active: true}, function (tabs) {
tabs.forEach((cur, i)=>{
chrome.tabs.sendMessage(tabs[i].id, {"delBody": true})
})
})
ContentScript:
chrome.runtime.onMessage.addListener(function(obj, sender) {
if(obj.delBody)
document.body.remove()
})

Thanks you very much wOxxOm. Problem was in
The background script runs when your extension is loaded on browser startup/update, when your content script haven't yet been injected
So I solve it like this:
content:
chrome.runtime.sendMessage({"getInfo": true})
chrome.runtime.onMessage.addListener(function(obj, sender) {
if(obj.delBody)
document.body.remove()
})
background:
chrome.runtime.onMessage.addListener(function(obj, sender) {
if(request.getInfo) {
chrome.tabs.query({active: true}, function (tabs) {
tabs.forEach((cur, i)=>{
chrome.tabs.sendMessage(tabs[i].id, {"delBody": true})
})
})
}
})

Related

No output to service worker console with chrome extension

I'm trying to build an extension to monitor the xhr portion of the devtools network tab. I decided to start as simple as possible with the background script below. I'm seeing no errors on loading the extension, but don't see any output in the console.
manifest.json:
{
"manifest_version": 3,
"version": "1.0",
"name": "Hello World!",
"description": "Learning how to make a chrome extension!",
"icons": {
"16": "images/puppy16.png",
"48": "images/puppy48.png",
"128": "images/puppy128.png"
},
"action": {
"default_icon": "images/puppy.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"host_permissions": [
"https://cnn.com/*"
],
"permissions": [
"webRequest"
]
}
In my background.js:
(function () {
chrome.webRequest.onCompleted.addListener(
function (details) {
console.log('HELLO THERE!!!!', details);
},
{ urls: ["<all_urls>"] }
);
}());
What am I doing wrong?

using background.js service_worker on about:blank page with matchAboutBlank:true not working, any workaround?

How can I run background.js (service_worker) in about:blank pages?
I want to do some JS inside Google Slide Presenter tab that opens as "about:blank" (when launching presenter from fullscreen browser).
I set "match_about_blank" : true for content_scripts and inside background.js I also tried using matchAboutBlank: true which didn't help.
I read that activeTab doesn't work with about:blank pages in another post, is there any other way I can achieve this?
manifest.json
{
"name": "Google Slide Presenter",
"description": "Highlight speaker notes with background colour",
"version": "0.1.0",
"manifest_version": 3,
"icons": {
"16": "/images/icon-16x16.png",
"32": "/images/icon-32x32.png",
"48": "/images/icon-48x48.png",
"128": "/images/icon-128x128.png"
},
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/icon-16x16_black.png",
"32": "/images/icon-32x32_black.png",
"48": "/images/icon-48x48_black.png",
"128": "/images/icon-128x128_black.png"
}
},
"content_scripts":[{
"matches": ["https://docs.google.com/*"],
"match_about_blank" : true,
"css": ["somecss.css"]
}],
"background": {
"service_worker": "background.js"
},
"permissions": [
"storage",
"activeTab",
"scripting",
"tabs"
],
"host_permissions": [
"https://docs.google.com/*"
]
}
background.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && /^http/.test(tab.url)) {
chrome.scripting.executeScript({
target: { tabId: tabId },
files: ["./foreground.js"],
matchAboutBlank: true,
})
.then(() => {
console.log("INJECTED THE FOREGROUND SCRIPT.");
})
.catch(err => console.log(err));
}
});
foreground.js
document.querySelector(".punch-viewer-speakernotes-text-body-scrollable").style.backgroundColor='yellow';
UPDATE - Able to run the JS but still with errors:
using content_scripts to load the js
"content_scripts":[{
"matches": ["https://docs.google.com/*"],
"match_about_blank" : true,
"css": ["progressbar.css"],
"js": ["foreground.js"],
"all_frames":true,
"match_origin_as_fallback":true,
"run_at": "document_start"
Using in foreground.js
setTimeout(function() {
const container = document.getElementsByClassName('punch-viewer-speakernotes-text-body-zoomable')[0];
if (container.textContent.includes('Speaker')) {
document.querySelector(".punch-viewer-speakernotes-text-body-scrollable").style.backgroundColor='yellow';
console.log('Speaker is contained in element');
} else {
console.log('Speaker is NOT contained in element');
document.querySelector(".punch-viewer-speakernotes-text-body-scrollable").style.backgroundColor='blue';
}
}, 5000);
CONSOLE:
Speaker is contained in element
Uncaught TypeError: Cannot read properties of undefined (reading 'textContent') at foreground.js:5:19
Uncaught TypeError: Cannot read properties of undefined (reading 'textContent') at foreground.js:5:19

Chrome extension does not work on the first installation

I am learning to how to make a chrome extension and trying to make popup js alert hello when a button is clicked.
background 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);
});
}
});
popup.js
document.addEventListener('DOMContentLoaded',function(){
$('#btnChange').click(function(){
chrome.tabs.query({active:true,currentWindow:true},function(tabs){
chrome.tabs.sendMessage(tabs[0].id,{todo:"clickAll"})})
});
});
content.js
chrome.runtime.sendMessage({todo:"showPageAction"});
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse)
{
if (request.todo =="clickAll"){
alert("alert");
}
});
manifest.json
{
"name": "alert",
"version": "1",
"description": "alert ",
"permissions": ["declarativeContent","activeTab","storage","https://*","tabs"],
"options_page": "options.html",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["https://*"],
"js": ["content.js", "jquery.js"],
"run_at": "document_start",
"all_frames": true
}
],
"page_action": {
"default_popup": "popup.html",
"default_icon": {
"128": "images/img.png"
}
},
"icons": {
"128": "images/img.png"
},
"manifest_version": 2
}
The code does not work when first time installed and requires refreshing to work. what can I do to make it work on first installation?

Accessing DOM in Chrome Extension

I'm using the example here as a starting point for accessing some DOM elements on the user's current tab. In popup.html, I have the following:
<script type="text/javascript" src="popup.js"></script>
And the first lines of popup.js are:
chrome.browserAction.onClicked.addListener(function(tab) {
// No tabs or host permissions needed!
console.log("test");
console.log('Turning ' + tab.url + ' red!');
chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="red"'
});
});
Manifest.json has the following permissions:
{
"manifest_version": 2,
"name": "",
"version": "1.0",
"description": "",
"icons": { "16": "icon16.jpg",
"48": "icon48.jpg",
"128": "icon128.jpg" },
"minimum_chrome_version": "46",
"browser_action": {
"default_icon": "icon48.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery.min.js", "getDescription.js"],
"run_at": "document_start"
}],
"options_page": "options.html",
"permissions": ["<all_urls>", "tabs","storage", "activeTab"]
}
Nothing is appearing in console, as if function isn't firing at all.
As it mention here onClicked fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.
If you want to have the popup and then to execute a script when the icon is clicked use below approach.
{
"name": "My Extension",
"version": "0.1",
"manifest_version" : 2,
"description": "la lala laa",
"background" : {
"scripts" : ["background.js"]
},
"browser_action": {
"default_icon": "icon48.png",
"default_popup": "popup.html"
},
"permissions": ["activeTab"]
}
Inside the background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "popup.js"});
});
Or it should work fine if you have below in your popup.html
<script src="popup.js"></script>
Inside your popup.js
window.onload = function() {
console.log("do whatever you want here !!!")
}

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