Chrome extension modify newtab page body? - javascript

I have chrome extension, which add new div to page body. But it doesnt work when i`m trying to run it on newtab page.
Here is my background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "commonAddWidget.js"};
});

I found that it can be resolved by adding content script, and sending a message to it after clicking on extension icon on browser.
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
if (url.indexOf('chrome://newtab') > -1) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {someObject: someValue});
});
}
}); });
contentScript.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {// this code can modify NewTab page, and will modify only it });

Related

popup.js can`t receive messages from background Chrome extension

I try this:
background.js
receive messages from popup.js (work fine)
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('chrome.runtime.onMessage');
console.log(request);
if (request&&request.method&&request.action) {
if($.isFunction(getLr()[request.method][request.action])) {
sendResponse(getLr()[request.method][request.action](request.data?request.data:undefined));
} else {
sendResponse(getLr()[request.method][request.action]);
}
}
});
send data to popup.js (don't work)
chrome.tabs.query({active: true}, function(tabs){
for(let t in tabs) {
chrome.tabs.sendMessage(tabs[t].id, $.extend({}, {method: method}, data), callback);
}
});
popup.js
send to background script (work fine)
chrome.runtime.sendMessage({method: method, action: action, data: data}, callback);
receive from background (don't work)
window.onload = function () {
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('chrome.runtime.onMessage');
});
};
what wrong?

how to send message from background to content script?

i am sending message from background to content script.
My background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
switch(request.type){
case "login-check":
checkLogin();
break;
}
});
function checkLogin() {
// var test = localStorage.getItem("test");
// alert(test);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {type: "login"}, function(response) {
console.log(response.farewell);
//alert(response.farewell);
});
});
}
My content-script.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type == "login")
sendResponse({farewell: "goodbye"});
});
it is showing me an error "Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined
".
i have tried all the ways almost but it didn't work please help.
thanks in advance

Chrome extension, how to send message from panel to content script

My contentScript sends a message to backgroundScript which opens a popup/panel/window. This panel loads an external web page.
I'm injecting some javascript in the panel to interact with it.
What I'm trying do achieve now is to send data from the panel to the 'main page' (contentScript).
I have successfully managed to send messages from the panel to the backgroundScript.
What I don't understand/know is how to pass the data from the backgoundScript to the contentScript.
Updated script from #Haibara Ai's comment
manifest.js
{
"name": "My extension",
"version": "0.1",
"manifest_version": 2,
"description": "description",
"permissions": ["activeTab", "tabs","http://*/*","https://*/*"],
"content_scripts": [
{
// Change 'matches' attribute to load content
// script only in pages you want to.
"matches": ["SomeUrl"],
"js": ["jquery.min.js", "contentscript.js", "notifier.js"]
}
],
"background": {
"scripts": ["eventPage.js"],
"persistent": false
}
}
contentscript.js
$(document).ready(function() {
var link = document.getElementById('inputLink');
// onClick's logic below:
link.addEventListener('click', function() {
chrome.runtime.sendMessage({
action: 'createWindow',
url: $('input[name=link]').val()
}, function(message) {
console.log(message);
})
});
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert('a');
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
eventPage.js
chrome.runtime.onMessage.addListener(function(request) {
if (request && request.action === 'createWindow' && request.url) {
chrome.windows.create(
{
url: request.url,
focused: true,
incognito: true,
type: "panel"
}, function (newWindow) {
chrome.tabs.executeScript(newWindow.tabs[0].id, {
file: "jquery.min.js"
}, function() {
chrome.tabs.executeScript(newWindow.tabs[0].id, {
file: "htmlselection.js"
});
});
chrome.tabs.insertCSS(newWindow.tabs[0].id, {file: "htmlselection.css"});
});
} else {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
console.log(chrome.tabs);
chrome.tabs.sendMessage(tabs[0].id, {action: "SendIt"}, function(response) {});
});
}
});
htmlselection.js (injected in the popup/panel/window)
[...]
//After a click within the popup/panel/window
chrome.runtime.sendMessage({ text: 'test' });
[...]
Thank you for your help.
Updated
If you want to send message inside chrome.runtime.onMessage, just use the callback sendResponse or use sender.tab.id as tabId to send back the message.
And there are other problems with your code:
Since you are use Programming injection to inject script, you should declare them in "web_accessible_resources" in manifest.json
"web_accessible_resources": [
"htmlselection.js",
"jquery.min.js",
"htmlselection.css"
]
In your contentscript.js, just remove message part, since you didn't receive anything in this script.
For eventpage.js, use sendResponse instead of tab.query.
else {
console.log("2");
sendResponse({ action: "SendIt" });
}
Previous
Take a look at Message Passing, you could send a message from background page using the following code snippets:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
Fixed version of the snippet:
chrome.tabs.query({active: true, currentWindow: false}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
Set the currentWindow:false and it worked.

How to send a message between Chrome extension popup and content script?

Following the Google tutorial, I am sending a message from a popup script to a content script. The message passes correctly but when I call the response callback I get the following error:
Attempting to use a disconnected port object
This is popup.js:
chrome.tabs.query(
{ active: true, currentWindow: true },
function(tabs) {
chrome.tabs.sendMessage(
tabs[0].id,
{ greeting: "hello" },
function(response) {
console.log(response);
});
});
This is content.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
sendResponse('goodbye'); // <- Error here
});
How can I send this message and get the response back?
This turned out to be due to an alert on the content page which caused the popup window to close. This in turn breaks the connection between the popup and the content script.
This example demonstrates sending a message to the content script in the selected tab.
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
reference Link

How to retrieve the active tab, inside message listener in background, in chrome extension?

I'm using the following code (in background.js) to get the active tab
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
console.log("active tab retrieved : " + tabs[0].id);
});
This works great, except for one case: when this piece of code is inside a messaging listener. For example the next scenario:
In background.js
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
console.log("message received");
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
console.log("active tab retrieved : " + tabs[0].id);
});
}
);
*in content_script.js*
chrome.runtime.sendMessage({}, function(response) {});
I only got the following in console
message received
and I didn't get the second log in console.
Why is this happening and how to solve it ?
There is an unclosed parenthesis in your code, which raises an exception and aborts execution. Correct it like this:
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
console.log("message received");
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
console.log("active tab retrieved : " + tabs[0].id);
}); // <-- add `);`
}
);
That said, if you just want to get the tab that sent the message, it is much easier:
sender.tab.id

Categories

Resources