Send message from popup to content script? - javascript

Suppose I want to run a content script when I click a button in the popup page in a google chrome extension?
I have tried the following:
//popup.js
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', clicked);
main();
});
function clicked(){
chrome.tabs.getCurrent(
function(tab){
console.log(tab);
chrome.tabs.sendMessage(tab.id, "doSomething");
}
);
}
And in the content script:
chrome.extension.onMessage.addListener(
function(message, sender, sendResponse){
console.log("hello world");
}
);
The problem is that the tab in the callback from chrome.tabs.getCurrent( ) is undefined.

Have you given permissions for tabs in manifest.json as shown here.
"permissions": [
"tabs"
],
Moreover tab.id which the following code returns is of popup view (NOT A CONTENT SCRIPT TAB.ID)
chrome.tabs.getCurrent(
function(tab){
console.log(tab);
chrome.tabs.sendMessage(tab.id, "doSomething");
}
);
If you want to send message to tab you are browsing use following code's tab.id, it gives correct results
chrome.tabs.query({"status":"complete","windowId":chrome.windows.WINDOW_ID_CURRENT,"active":true}, function(tabs){
console.log(JSON.stringify(tabs[0]));
console.log(tabs[0].id);
});
Let me know if you need more information

The answer provided by #Sudarshan is valid and works fine, but I just found another solution to my problem. Just thought i put it here:
function clicked() {
chrome.tabs.executeScript(null,
{code:"console.log('hello world');"});
}
It will inject and execute the script.

Related

Chrome extension window onload jquery

How am I going to write something when user clicks extension icon and loads the window?
I've already tried
window.onload = function() {
console.log("das");
}
and ]
$(document).ready(function(){
console.log('document is ready');
});
but still there isn't any log?
Maybe it's not the best idea but you can use chrome.tabs.sendMessage and chrome.runtime.onMessage.addListener to communicate between contentscript.js and popup.js
contentscript.js is running directly in page scope so you can easily detect when page is ready. After that you can send a message chrome.tabs.sendMessage(tabs.id, {action: 'pageReady'});. In popup.js you are listening to:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'pageReady') {
// Do what you want to do on page ready
}
});
It should works good for you. You can also send response to the caller:
contentscript.js send information to the popup.js that page is ready.
popup.js do what you want to do (show table).
popup.js send information to the contentscript.js that table is added.
EDIT
I'm not sure about my solution because I found information that:
The popup, while being an extension page, is not a background page. It
is only accessible when it is open
I don't know if it is possible to listen on events in popup. You need to check it.

OnActivated is only working when new tab opened

I'm trying to communicate with the content script of the tab that has just been switched to using message passing. Here is my code in the background.js script.
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.sendMessage(activeInfo.tabId, { greeting: "hello" }, function(response) {
console.log(response.farewell);
});
});
And here is my code in my content script:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
sendResponse({ farewell: "goodbye" });
loadContent();
});
Is the content script no longer listening in an inactive tab even when it's switched back to that tab? Why does this only run in a newly opened tab?
To further clarify why I want to do this, sometimes tabs are left open without reloading, and my script has already been executed. When information pertaining to the script changes using the popup options, I want the content to reload on tab change, and a particular function to run again without reloading the page. Therefore, injecting the content script is less than ideal since it's already been executed.
Try this :
background.js
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
chrome.tabs.sendMessage(activeInfo.tabId,
{ greeting: "hello" }, function(response) {
console.log(response.farewell);
});
});
});

Chrome Extension popup.html html injection from with background script

currently i am using the chrome.browserAction.onClicked.addListener to call a method from crap.js everytime the icon is clicked and set up the popup page.
chrome.browserAction.onClicked.addListener(function (tab) { //Fired when User Clicks ICON
chrome.tabs.executeScript(tab.id, {
"file": "js/crap.js"
}, function () { // Execute your code
console.log("Script Executed .. "); // Notification on Completion
});
chrome.browserAction.setPopup({
popup: "popup.html"
});
});
I have the following jquery code on content.js integrated in both scrip in popup.html and manifest.json
$( "p" ).append( "test" );
$( "#sectionA" ).html( "<p>All new content. <em>You bet!</em></p>" );
But it doesn't seem to work. I was wondering if it is possible to pass my values from select.js to content.js in the background to popup.html.
Also i have noticed that everytime i set up the popup html i am not able to call crap.js again. is there a workaround for this?
many thanks,
John

Executing script on a precise tab in Google Chrome extension

I want to execute a script on a precise tab of my browser. This script will give back a value.
I don't know what I have to use. The Doc says that contentScript are called on every loading of a new page. I just want to execute the script once the user clicked on a button in my popup.html.
In your contentScript file add listener like this:
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
//do job
sendResponse(...);
});
And in your popup.html on click event:
chrome.tabs.sendMessage(tabid, "message", function responseCallback(response) {
//...
});
more info http://developer.chrome.com/extensions/tabs.html#method-sendMessage

How can I communicate between background.js and popup.js?

I have an extension, with a background script:
"background": {
"scripts": ["scripts/background.js"]
},
and a content script:
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["scripts/content_script.js"]
}
],
a popup window (popup.html), and a popup script (popup.js). popup.js is not registrated into manifest,and it deals with popup.html look, and listen for user actions made in popup.html, such as clicking a button.
I want to make an extension, what emails the current tab's page, and for this, I need to get the page DOM with the content_script, pass data (DOM) to the background script. After this, when the user triggers an event in popup.html, popup.js catches this event, and I want popup.js to be able to get the passed data(DOM) from background.js. How could I make this? So, my question is, how could I communicate between background.js and popup.js?
I found an answer to my own question:
Thanks Elvis, I think I solved the problem; I only need to get the DOM of site in content script, but my question's solution was this:
content_script.js
// SEND DOM structure to the background page
chrome.extension.sendRequest({dom: "page DOM here"});
background.html
<html>
<head>
<script>
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.dom != "")
var theDOM = request.dom;
console.log(request.dom); // page DOM here -> works
chrome.extension.sendRequest({theDOM: theDOM}); // theDOM : "page DOM here"
});
</script>
</head>
<body>
</body>
</html>
popup.js
var dom;
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.theDOM != ""){
console.log("popup request: "+request.theDOM);
dom = request.theDOM;
}
});
// HANDLE TAB_1 REQUESTS (EMAIL PAGE)
// ---------------------------------
$("#send").click(function(){
console.log(dom); // page DOM here
}
Thanks for the help ;)
You can do Message Passing. From the documentation:
Use this in your content script:
chrome.extension.sendRequest({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
It sends {greeting: "hello"} to the background. Notice the callback specified
The background page can listen to these requests using:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
The arguments to the sendResponse function will be passed to the callback

Categories