Sorry for the relatively broad title... So I have a pretty basic chrome extension with a Popup(html\js) and a content page.
Basically all the extension does is put a button on the popup page that when clicked sends a message to the content script to check all check boxes on the page. The code is pretty basic but it is breaking stuff like dropdown menus and general formatting.
Here is all of my code, like I said it's not much. Any ideas what could be going on?
Content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "toggle_checkboxes" ) {
$(':checkbox').each(function() {
if(this.checked)
this.checked = false;
else
this.checked = true;
});
}
else{
//alert("nothing caught, here is the message:" + request.messgae);
}
}
);
popup.js
function toggle_checkboxes() {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "toggle_checkboxes"});
});
}
document.getElementById('toggle_checkboxes').addEventListener('click', toggle_checkboxes);
Related
I'm attemtping to send a message from the content script to the background script, and send a response in return.
This is what I've got in my background script:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("Message received");
if(request.activeStatusRequest == "disable"){
sendResponse({activeStatusUpdate: "disable"});
}else if(request.activeStatusRequest == "enable"){
sendResponse({activeStatusUpdate: "enable"});
}
return true;
});
This is what I've got in my content script:
printReviews.onclick = function(element) {
if(printReviews.classList.contains("activeButton")){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(
tabs[0].id,
{code: `${injectionLiteralGETURL}`}
);
});
toggleClasses(printReviews, "activeButton", "inactiveButton");
chrome.runtime.sendMessage({activeStatusRequest: "disable"}, function(response){
console.log("response received");
console.log(response.activeStatusUpdate);
});
}
else {
toggleClasses(printReviews, "inactiveButton", "activeButton");
chrome.runtime.sendMessage({activeStatusRequest: "enable"}, function(response){
console.log("response received");
console.log(response.activeStatusUpdate);
});
}
};
The rest of the above code works as expected, except that the none of the console logs in the content script run. The console log in the background script does run, however.
Anyone got any ideas as to what I've done wrong?
If you want to try another method, you could try to add a listener in the content script
Content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("Message received from background", response.type, response.activeStatusUpdate);
switch(request.type){
case 'SomeFirstAction'
break;
case 'SomeSecondAction'
break;
}
});
Background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("Message received");
if(request.activeStatusRequest == "disable"){
sendMessageToCurrentTab({type: 'SomeFirstAction', activeStatusUpdate: "disable"});
}else if(request.activeStatusRequest == "enable"){
sendMessageToCurrentTab({type: 'SomeSecondAction', activeStatusUpdate: "enable"});
}
// return true; -> not needed with that method
});
function sendMessageToCurrentTab(message){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, message);
}
}
To have played with callbacks between popup/background/content-script, I prefer just play with messages,because when using sendResponse, the manner it works, it open a port to communicate, but if something change (tab close, popup close), you will have an error because the port will be closed too.
Using the 'Full send message manner', the background need to clearly target the receiver tab.
I also recommand you to use a type or some unique action attribute, because all listener will listen to all action. It will identify the action and it's purpose.
Here I just used a switch in the content script, but the background could use the same logic.
Maybe it's not the greatest way of doing things, but it works well for me.
Hope this can help you
I'm currently building an extension for chrome (I'm a beginner) and looking for some help to some one issue. The flow of the extension is the following:
User activate the extension
User click an icon in the extension panel to start the capture
When the mouse cursor is over a DOM element it highlight it
When the user click it gets the "selector" (unique identifier/path to the element)
After step 2 I attach a new Debugger instance to the tab. it seems like you can do this action either in background.js or content-script.js. Both work so my question is which one makes more sense. I'd say content-script because it doesn't interact directly with the browser but only with my extension. Am I right?
Second question is when using the DebuggerAPI I need to send command using the DevTools Protocol Viewer. I guess the command I must send to interact with my DOM element sit under this category (https://chromedevtools.github.io/devtools-protocol/tot/DOM). Most of the command requires a NodeId parameter. My question is how would I get this NodeId when the mouse cursor is over it. I have the following event in my content-script
chrome.runtime.onMessage.addListener(function(msg, sender){
if(msg == "togglePanel"){
togglePanel();
} else if (msg == "startCaptureElement") {
console.log("- Content-Script.js: Add Mouse Listener");
document.addEventListener('mouseover', captureEvent);
} else if (msg == "stopCaptureElement") {
console.log("- Content-Script.js: Remove Mouse Listener");
document.removeEventListener('mouseover', captureEvent);
}
});
function captureEvent(el) {
//console.log("- Content-Script.js: It's moving");
console.log(el);
chrome.runtime.sendMessage("highlightElement");
}
In my background.js script
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender);
if (request == "startCaptureElement") {
console.log("- Background.js: Attach the debugger");
chrome.debugger.attach({tabId: sender.tab.id}, "1.0");
chrome.tabs.sendMessage(sender.tab.id, "startCaptureElement");
} else if (request == "stopCaptureElement") {
console.log("- Background.js: Detach the debugger");
chrome.debugger.detach({tabId: sender.tab.id});
chrome.tabs.sendMessage(sender.tab.id, "stopCaptureElement");
} else if (request == "highlightElement") {
console.log("- Background.js: Highlight Element");
chrome.debugger.sendCommand({tabId: sender.tab.id}, "DOM.enable", {});
chrome.debugger.sendCommand({tabId: sender.tab.id}, "Overlay.inspectNodeRequested", {}, function(result) {
console.log(result);
});
}
}
);
I found the similar question here How to highlight elements in a Chrome Extension similar to how DevTools does it? but the code provided confused me a little bit.
Thanks for your help
"Overlay.inspectNodeRequested" is an event that should be listened to.
you can call "Overlay.setInspectMode" to select a node.
background.js:
var version = "1.0";
//show popup page while click icon
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.debugger.attach({tabId:tab.id}, version,
onAttach.bind(null, tab.id));
});
function onAttach(tabId) {
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
return;
}
chrome.windows.create(
{url: "headers.html?" + tabId, type: "popup", width: 800, height: 600});
}
headers.html:
<html>
<head>
<meta charset="utf-8">
<script src="headers.js"></script>
</head>
<body>
<div id="container">
<button id="btn_inspect">select node</button>
</div>
</body>
</html>
headers.js:
var tabId = parseInt(window.location.search.substring(1));
var hightCfg = {
'showInfo': true, 'showStyles':true, 'contentColor':{r: 155, g: 11, b: 239, a: 0.7}
}
//listen events when page is loaded
window.addEventListener("load", function() {
chrome.debugger.sendCommand({tabId:tabId}, "DOM.enable");
chrome.debugger.sendCommand({tabId:tabId}, "Overlay.enable");
chrome.debugger.onEvent.addListener(onEvent);
document.getElementById('btn_inspect').addEventListener('click', function(){
chrome.debugger.sendCommand({tabId:tabId}, "Overlay.setInspectMode",
{'mode':'searchForNode', 'highlightConfig':hightCfg});
});
});
window.addEventListener("unload", function() {
chrome.debugger.detach({tabId:tabId});
});
var requests = {};
function onEvent(debuggeeId, message, params) {
console.log('onEvent ...'+message);
if (tabId != debuggeeId.tabId)
return;
if (message == "Network.inspectNodeRequested") {
//do something..
}
}
i'm having a lot of trouble with Chrome Extensions, im trying to close all open tabs that do not contain a certain class.
This is the general idea of what i am trying to do, some of it is pseudo-code.
//background.js
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.query(function(tabs) {
chrome.tabs.sendMessage(tabs, {"message": "clicked_browser_action"});
});
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
for (var i = 0; i < request.length; i++) {
var existsClass = request[i].getElementByClass("someClass");
if (existClass === null) {
//TODO Close tab
}
}
}
}
);
Any help or suggestions would be appreciated.
Thanks!
I'm assuming your second snippet is from a content script.
In that case, it's as simple as window.close(), because you're in that tab's context. No need for Chrome APIs.
Try this:
//background.js
chrome.browserAction.onClicked.addListener(function () { //when the extension's icon is pressed
chrome.tabs.query({},function(tabs) { // get all tabs
for (var i = tabs.length; i--;){ // loop through all tabs
chrome.tabs.executeScript(tabs[i].id,{code: //execute this code in each tab
"if (!document.querySelector(\".someClass\")) close();"});
// ^ if no element is found with the selected class, close the tab
}
});
});
You don't need a separate content script for that.
I want to run a content script to identify the first image that links somewhere and return the link to the background script. But I can't pass any messages between them, and I don't know why. Much of the code is comment, I'm trying to simply test if the content script is executing by telling it to change the first header to "test" (since the only thing I can do without messages is change a page's HTML and CSS). The code follows:
EDIT: full updated code
Background script:
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.query({active:true, currentWindow:true}, function(tabs)
{
chrome.tabs.executeScript(tabs[0].id, {file:"content.js"}, function ()
{
console.log("sending first time");
console.log(tabs[0].id);
chrome.tabs.sendMessage(tabs[0].id,{test: "test"}, function (response)
{
if (undefined == response)
{
console.log ("first one didn't work");
chrome.tabs.sendMessage(tabs[0].id, {test: "test"}, function (response)
{
console.log(response.test);
});
}
});
});
});
});
Content Script:
chrome.runtime.onMessage.addListener( function (msg, sender, sendResponse)
{
/*var test1 = document.getElementsByTagName("h1")[0];
test1.innerHTML="test";*/
sendReponse({test: "123"});
/*var parentList =document.getElementsByTagName("a");
var link = "";
var child;
for (var i=2; i<parentList.length;i++)
{
child=parentList[i].firstChild;
if ("IMG"==child.nodeName)
{
link=parentList[i].href;
break;
}
}
teste1.innerHTML=link;
var answer = new Object();
Answer.link = link;
teste1.innerHTML=answer.link;
sendResponse({messager:answer});*/
});
I was testing the extension at the extension page itself. But it seems you can't inject javascript in it (probably because it is a browser's settings page). It worked nicely on other pages.
I'm the maker of an addon called BeautifyTumblr which changes the apperance of Tumblr.
I wish for my Chrome extension to automatically detect when it has been updated and display changelog to the user. I use an event page with the chrome.runtime.onInstalled.addListener hook to detect when an update has occured, retrieve the changelog from a text file in the extension.. this all works fine, then when I want to forward it to my content script via chrome.tabs.sendmessage it just wont work, nothing ever happens, no errors no nothing. I'm stumped.
Any help would be much appreciated!
Event Page:
chrome.runtime.onInstalled.addListener(function (details) {
"use strict";
if (details.reason === "install") {
} else if (details.reason === "update") {
var thisVersion = chrome.runtime.getManifest().version, xmlDom, xmlhttp;
xmlDom = null;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", chrome.extension.getURL("changelog.txt"), false);
xmlhttp.send(null);
xmlDom = xmlhttp.responseText;
chrome.tabs.query({'url' : 'http://www.tumblr.com/*'}, function (tabs) {
if (tabs.length > 0) {
var mTab = tabs[0].id;
chrome.tabs.update(mTab, {active: true});
setTimeout(chrome.tabs.sendMessage(mTab, {beautifyTumblrUpdate: xmlDom}), 500);
} else {
chrome.tabs.create({'url' : 'http://www.tumblr.com/dashboard'}, function (tab) {
setTimeout(chrome.tabs.sendMessage(tab.id, {beautifyTumblrUpdate: xmlDom}), 500);
});
}
});
}
});
Relevant code in Content Script:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
"use strict";
window.alert('test');
if (request.beautifyTumblrUpdate) {
window.alert(request.beautifyTumblrUpdate);
} else if (request.beautifyTumblrInstall) {
window.alert(request.beautifyTumblrInstall);
}
}
);
I am also seeing the same thing. I am not a 100% sure but I think this happens because chrome shuts off connection between background page and "old" content scripts the moment the extension is updated. There's more info here in this bug : https://code.google.com/p/chromium/issues/detail?id=168263
simple, use the following code in background,
chrome.runtime.onInstalled.addListener(function(details){
if(details.reason == "install"){
chrome.tabs.create({ url: chrome.extension.getURL('welcome.html')});
}
});