Popup.html is the same in all tabs (Chrome extension) - javascript

My extension checks for broken images on a website. Everything works fine if I open an URL at a time but if I open several URLs from one site, the summary in popup.html is always the same as the active tab (it's not updated for each site).
I don't know how to refer to the actual URL of the analysis and avoid the "active tab". Any ideas?
Manifest.json
{
"name": "Test",
"permissions": ["activeTab", "declarativeContent", "storage","tabs"],
"version": "1.0.0",
"description": "Test",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*", "https://www.google.com/_/chrome/newtab*"],
"exclude_globs": ["*#*"],
"js": ["jquery-3.4.1.min.js", "content.js"]
}
],
"web_accessible_resources": ["popup.html"],
"browser_action": {
"default_icon": {
"16": "images/ico.png",
"32": "images/ico.png",
"48": "images/ico.png",
"128": "images/ico.png"
}
},
"manifest_version": 2
}
Content.js
chrome.runtime.onMessage.addListener((msg, sender, response) => {
if (msg.subject === 'DOMInfo') {
var domInfo = {
images: number_images
};
response(domInfo);
}
});
Popup.js
window.addEventListener('DOMContentLoaded', () => {
chrome.tabs.query({
active: true,
currentWindow: true
}, tabs => {
chrome.tabs.sendMessage(
tabs[0].id,
{subject: 'DOMInfo'},
setDOMInfo);
});
});
I'm pretty sure is the tabs[0].id that causes the problem but I'm not sure how I can refer to the current URL that run the content.js script and make sure the popup.html gets the analysis from this URL. Any ideas?
In the background.js I had no problem referring the sender tab:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse)
{
chrome.tabs.query({active:true, windowType:"normal", currentWindow: true},function(d){
var tabId = sender.tab.id;
....

Assuming popup.html is loaded into an iframe inside the web pages by your content script, you need chrome.tabs.getCurrent that returns the tab where this code is running so each iframe will find its own tab:
chrome.tabs.getCurrent(tab => {
chrome.tabs.sendMessage(tab.id, {subject: 'DOMInfo'}, callback);
});
P.S. When using sender.tab.id you don't need chrome.tabs.query - you already have the id.

Related

Content Script is not executing in new tab after page load

Creating chrome extension which opens link in new tab and trying to click the button on newly opened tab -
I am able to open new tab using the extension but the content script is not executing on new tab.
Manifest File
{
"manifest_version": 2,
"name": " New Tab Launcher",
"description": "Create the tab and button click ",
"version": "1.0",
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs"
],
"content_scripts": [
{
"matches": [
"http://*/*", "https://*/*"
],
"js": [
"jquery-3.6.0.slim.min.js","contentScript.js"
],
"run_at": "document_end"
}
]
}
popup.js
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('addMeetingUrl');
checkPageButton.addEventListener('click', function() {
chrome.tabs.create({'url': "youtube.com"});
}, false);
}, false);
contentScript.js
alert("This is test");
$(document).load(function (e) {
alert("Testing content script" +$('#logo').text());
});
In above the first alert come successfully by next script does not launch.
I have tried Removing the $(document).load and adding $(document).ready both are not working for me.
#logo could be added to the DOM after the load and ready events are fired.
Check with the debugger if I've stated is true.
If so you will need to use MutationObserver.
Try removing "run at" as it will default to "document_idle" which is usually safer option

Cant send message from background script to content script

I'm trying to send a message from the background script to the content script and it doesn't work, tried multiple solutions I found but none of them work.
I checked that the background and content scripts both work correctly.
I tried to use chrome.runtime\extention and also with message and request...
hope you could tell me what I'm doing wrong.
manifest:
{
"manifest_version": 2,
"name": "ChangeLang",
"description": "change written text lang",
"version": "1.3",
"permissions": ["storage", "contextMenus", "activeTab", "tabs"],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"browser_action": {
"name": "Click to change the icon's color"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["changelang.js"]
}],
"background": {
"scripts": ["background.js"]
}
}
background.js:
chrome.browserAction.onClicked.addListener(function(info, tab) {
alert("click"); // this alert works
chrome.tabs.sendMessage(tab.id, {
"functiontoInvoke": "change"
});
alert("click"); // this alert doesn't works
});
content.js:
function changeLang() {
// do something
}
chrome.runtime.onMessage.addListener(function(message, sender, callback) {
alert("msg"); // never worked
if (message.functiontoInvoke == "change") {
changeLang();
}
});
I think your code setup should look like this:
chrome.browserAction.onClicked.addListener(function(info, tab) {
alert("click"); // this alert works
chrome.tabs.sendMessage(tab.id, {
"functiontoInvoke": "change"
}, function(response) {
response.yourFunc();
});
alert("click"); // this alert doesn't works
});
chrome.runtime.onMessage.addListener(function(message, sender, callback) {
alert("msg"); // never worked
if (message.functiontoInvoke == "change") {
callback({yourFunc: changeLang()});
}
});

Firefox addon: sendMessage not working in tabs.onUpdated but does in browserAction.onClicked (background.js)

I'm working on migrating my Chrome extension into a Firefox addon. Honestly didn't think it would be that hard, but I've been trying to fix an issue of the background not wanting to send a message to the content script. (And yes, I've read everything online, but it just won't send the message inside an onUpdated listener)
EDIT
When I tried to put following line into the browserAction.onClicked listener it works, but it does not work in onUpdated?
browser.browserAction.onClicked.addListener(function(tab) {
browser.tabs.sendMessage(tab.id, {action: "isInstalled"});
});
END EDIT
And yes, the content script IS loaded, checked with an alert for the hostname.
Here's the code I used in the Chrome extension (background):
chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
chrome.tabs.sendMessage(tab.id, {
action: 'isInstalled'
});
});
Now here's what I have tried in Firefox addon (background):
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => {
browser.tabs.sendMessage(tabs[0].id, {greeting: "hello"});
});
Which is inside the browser.tabs.onUpdated listener as follows:
browser.tabs.onUpdated.addListener(function(tabId, changeInfo, tabInfo){
if(changeInfo.status === "complete"){
...
}
});
I also tried this, as I thought it would work: (yes tabId is correct).
browser.tabs.sendMessage(tabId, {action: "isInstalled"});
Now here's the onMessage listener on content script
browser.runtime.onMessage.addListener(function(request, sender) {
if(request.action == "isInstalled"){
alert("received");
var isInstalledNode = document.createElement('div');
isInstalledNode.id = 'extension-is-installed';
document.body.appendChild(isInstalledNode);
}
});
I keep getting the following error: "Error: Could not establish connection. Receiving end does not exist." which makes absolutely no sense for me.. Can anyone see the problem?
By the way, here's the manifest file:
{
"name": "Addon name",
"version": "1.3.0",
"manifest_version": 2,
"description": "...",
"icons": {
"48": "assets/images/icon_48_active.png",
"96": "assets/images/icon_96_active.png"
},
"browser_action": {
"default_title": "Name"
},
"background": {
"scripts":["background.js"]
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["contentscript.js"]
}
],
"permissions": [
"cookies", "tabs", "http://*/*", "https://*/*"
],
"web_accessible_resources": [
"modal.html", "assets/images/*"
]
}

Is it possible to run javascript after a page has loaded using a omnibox extension?

I am trying to build an omnibox extension. Essentially I want this extension to pull up a url, then wait for that url to load, then execute some simple javascript.
Not sure if it's appreciated to put long blocks of code in questions, please feel free to yell at me if not.
manifest.json:
{
"manifest_version": 2,
"name": "AutoATR",
"version": "0.1",
"omnibox": { "keyword" : "atr" },
"icons": {
"16": "package.png"
},
"background": {
"persistent": true,
"scripts": ["background.js"]
}
}
background.js:
function resetDefaultSuggestion() {
chrome.omnibox.setDefaultSuggestion({
description: 'atr: Placeholder: %s'
});
}
resetDefaultSuggestion();
function navigate(url) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
chrome.tabs.update(tabs[0].id, {url: url});
});
}
function finder(theID) {
document.getElementById('theElement').value=theID
document.getElementsByClassName('btn')[1].click()
}
chrome.omnibox.onInputEntered.addListener(function() {
// Navigate to URL
navigate("https://theURL.com");
});
// **** Would like to wait for just this tab to load.
// Then Execute finder(). ****
You can use manifest for your task:
change location in background script location of tab to your pathURL and in manifest.json add next code :
"content_scripts": [{
"matches": ["http://pathURL"],
"js": ["js/script.js"]
}]
js/script.js will be loaded after your browser tab path will match with "http://pathURL" pattern.

google chrome extension browserAction.onClicked

i can't figure out how to make it work. My script works by itself. but doesn't work with background.js. I want my google extension to work only if the user clicks on it's icon, so I have created the file background.js and putted the code:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "change_content.js"});
});
my manifest.json here:
{
"manifest_version": 2,
"name": "Name",
"description": "change content.",
"version": "3.0",
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["change_content.js"]
}
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"tabs", "http://*/*"
]
}
and here is the change_content.js:
var oldSource = document.documentElement.innerHTML;
document.body.innerHTML = changeContent(oldSource);
function changeContent(source){
.....
}
The reason you are having the issue where change_content.js is executing before you press the button is because thats how content scripts work. If you include a content script in your manifest.json it will load and execute that script. Try removing the "content_scripts" section from the manifest and you should see it work as it should.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "change_content.js"});
});
I've got a feeling the error lies in you using "null" as it might be searching for a tab with the tabId - null, you should try doing this instead?
chrome.tabs.executeScript({file: "change_content.js"});

Categories

Resources