I should send data from my devtools panel to tab. When I send a message using chrome.tabs.sendMessage, why is it not received?
panel.js
$(".options").on("submit", "form", function(e) {
e.preventDefault();
newTabPort = chrome.runtime.connect({ name: "new tab" });
newTabPort.postMessage($(this).serializeArray());
});
background.js
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(message) {
console.log(message);
});
if (port.name == "new tab") {
chrome.tabs.create({'url': chrome.extension.getURL('page/request_sending_page.html')}, function(tab) {});
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {message: "olololololololo"});
});
}
});
my_extension_page.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
$("body").append("Hello world <br>");
$("body").append(request.message);
});
Thank you!
All Chrome API with function callbacks are asynchronous, so in your code chrome.tabs.create is executed after the entire function code has completed, thus chrome.tabs.query on the next line doesn't see the newly created tab.
Move the code that should work with the result of the asynchronous call into the callback
Wait for the new tab to be completely loaded before sending the message
There's no need for chrome.extension.getURL when you open the tab from background script.
chrome.tabs.create({url: '/page/request_sending_page.html'}, function(tab) {
var newTabId = tab.id;
chrome.tabs.onUpdated.addListener(function onComplete(tabId, info, tab) {
if (tabId == newTabId && info.status == "complete") {
chrome.tabs.onUpdated.removeListener(onComplete);
chrome.tabs.sendMessage(tabId, {message: "olololololololo"});
}
});
});
P.S. manifest.json: "permissions": ["tabs"]
Related
I'm want to create an overlay via content script (content.js) for my google chrome extension. How should I do this?
Here is the code that executes the content script:
chrome.webNavigation.onCommitted.addListener(function() {
chrome.windows.getCurrent(function (currentWindow) {
chrome.tabs.query({ active: true, windowId: currentWindow.id }, function (activeTabs) {
activeTabs.map(function (tab) {
chrome.tabs.executeScript(tab.id, { file: 'contentScript.js', allFrames: false });
});
});
});
}, {url: [{urlMatches : 'https://mail.google.com/'}]});
Here is my contentScript.js
window.addEventListener('DOMContentLoaded', setUpOverlay, false);
function setUpOverlay(){
//Set up overlay div in here
}
The best way to achieve what you want is to use the chrome message api and pass a message to the content script to execute the code
here is how it works:
//popup.js
chrome.tabs.query({active:true,currentWindow:true},(tabs)=>{
chrome.tabs.sendMessage(tabs[0].id,'execoverlay',(resp)=>{
console.log(resp.msg)
})
})
//contentScript.js
chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{
if(request==='execoverlay'){
// your code goes here
sendMessage({msg:'recieved'})
}
})
I made a Chrome extension to do some routine tasks that I have to do as checking some values and clicking some buttons.
It works really well when it's on focused tab but it stops working when it is in background or not focused.
My background.js:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == 'complete') {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
//checking something
chrome.tabs.query({currentWindow: true, active: true},
function(tabs) {
chrome.tabs.sendMessage(tab.id, {type: 1});
});
});
}
});
My content.js:
chrome.runtime.onMessage.addListener(function(request, sender, response) {
if(request.type == 1) {
//actions
}
});
I don't really know what I can do to let this works in background too.
Thanks for the help
I am trying to build a simple chrome extension to get a value from a page and populate a second page after.
I'm new to chrome extensions, and I'm really only doing this to make something I have to do often simpler.
So I got the part where I open the first page, get the value I need and then I open the second page in another tab. Now I'm not sure how to populate the field.
Since I already have the value on content.js, is it possible to know when the other tab has loaded to just look for the field where i need to put that value in? Or is there another way to do it? I can't get it to work.. I also tried to listen to page loads, but I don't think that will help me, as I'm only interested in one particular page.
Manifest:
{
"manifest_version": 2,
"name": "my Extension",
"version": "1",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["jquery-3.2.1.min.js", "content.js"]
}
],
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
}
}
background.js
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
// Send a message to the active tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});
//
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "open_new_tab" ) {
chrome.tabs.create({"url": request.url},
function(tab){ alert(tab.id) });
}
}
);
chrome.tabs.onUpdated.addListener(function (tabId , info) {
if (info.status === 'complete') {
chrome.tabs.sendMessage(activeTab.id, {"message": "page_loaded"});
}
});
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
var myUrl = "http://www.google.com";
var myValue = document.getElementById("thisId").value;
if(myValue ) {
chrome.runtime.sendMessage({
"message": "open_new_tab",
"url": myUrl,
"myValue ": myValue
});
}
}
if( request.message === "page_loaded" ) {
alert("hi");
}
});
I managed to pass a message between two files/instances, namely my popup and my background scripts, but the callback function still returns undefined, so my popup script does not receive a reply. Can somebody assist me? My code is based on the docs from Google.
Background.js
chrome.runtime.onMessage.addListener(function (sender, sendResponse) {
var resp = {'navURL': "Not set yet"};
if (sender.greeting === "GetURL") {
sendResponse(resp);
}
});
popup.js
function getURL() {
chrome.runtime.sendMessage({
greeting: "GetURL"
},
function (response) {
// RESPONSE IS UNDEFINED //
console.log(response);
alert(response.navURL);
});
}
$("input[type='checkbox']").on('change', function () {
getURL();
});
Manifest.json
{
"name": "FaceBlock",
"description": "This extention gets rid of unwanted content on Facebook like sponsored posts, adds or annoying suggestions. The content you wish to see is enlarged for a better and richer social experience.",
"version": "0.0.1",
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"http://*.facebook.com/*", "https://*.facebook.com/*"],
"css": ["css/popup.css"],
"js": ["js/jquery.min.js", "js/content.js"],
"run_at": "document_end",
"all_frames": true
}],
"options_page": "options.html",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Faceblock"
},
"permissions": [
"activeTab",
"tabs",
"https://www.facebook.com/*",
"https://ajax.googleapis.com/",
"storage"
],
"background": {
"scripts": ["js/background.js"],
"persistent": false
},
"options_ui": {
// Required.
"page": "popup.html",
// Recommended.
"chrome_style": true
// Not recommended; only provided for backwards compatibility,
// and will be unsupported in a future version of Chrome (TBD).
//"open_in_tab": true
},
"web_accessible_resources": [
"images/faceblock.jpg",
"images/seigaiha.png",
"js/popup.js",
"icon.png",
"js/options.js",
"css/popup.css",
"popup.html",
"options.html"
]
}
Thanks in advance,
Niels Vermeiren
EDIT: I now have the following with the same problem
Background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
sendResponse({msg: "Element " + sender.element + " zijn zichtbaarheid wordt nu: " + sender.checked});
return true;
});
Popup.js
function getCurrentTabUrl(callback) {
return new Promise(function (resolve, reject) {
// https://developer.chrome.com/extensions/tabs#method-query
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function (tabs) {
if (callback(tabs[0].url)) {
return resolve();
} else {
return reject();
}
});
});
}
function changeFacebook(data) {
console.log(data);
chrome.runtime.sendMessage(
"changeFacebook",
data,
function (response //undefined) {
console.log(response.msg); // UNDEFINED
});
}
document.addEventListener('DOMContentLoaded', function () {
var callback = function getCurrentTab(tab) {
if (tab == "https://www.facebook.com/") {
return true;
} else {
return false;
}
}
getCurrentTabUrl(callback).then(function () {
alert('on facebook');
$('.section').hide();
}, function () {
alert('not on facebook');
});
$("input[type='checkbox']").on('change', function () {
var id = $(this).attr('id');
var check = this.checked;
var data = {
'element': id,
'checked': check
};
changeFacebook(data);
});
$('.menuItem').hide();
$('.menuItem:first').show();
jQuery('.navitem').on('click', function () {
var value = $(this).html().toLocaleLowerCase();
jQuery('.menuItem').hide();
jQuery('#' + value).show();
});
});
According to doc here:
https://developer.chrome.com/extensions/runtime#event-onMessage
In your background.js, it should be
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
...
});
Since you are missing the last argument, what you really have is this:
chrome.runtime.onMessage.addListener(function (request, sender) {
...
});
So your code pretty much renamed request => sender, sender => sendResponse.
Therefore, you are trying to invoke sender as a function. But the actual sendResponse callback function is undefined. If you inspect your background page (see tips for how), you should see the error.
Tips:
When developing chrome extension, you can Inspect views: background page in the chrome://extensions page if you have any background page running.
When your popup is opened, you can inspect the popup page just you normally do.
And you can throw debuggers wherever you want, and you will be able to play around with it.
Edit:
So I have tested your code, the issue is just missing argument as I stated above. I also noticed the doc says the first two arguments are optional (not sure what the fuzz that is). But if you change your code to as below, it will work.
Background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
var resp = {'navURL': "Not set yet"};
if (request.greeting === "GetURL") {
sendResponse(resp);
}
});
Popup.js
function getURL() {
chrome.runtime.sendMessage({
greeting: "GetURL"
},
function (response) {
console.log(response);
alert(response.navURL);
});
}
To test it
Go to the background page inspect, and paste in the background page snippet.
Go to the popup page inspect (open your popup, and right click within the popup, then choose inspect)
Paste in the popup page snippet
In the popup page inspect, call getURL()
I am writing a small extension that allows me to easy submit links to reddit.
This extensions adds a new context menu ('Submit Page'). If the users right clicks and selects this menu the www.redddit.com/submit page is opened in another tab, and the page from where the menu was triggered is submitted.
I've added the context menus:
contextMenu.js
// Setup where the menu is presents;
// A list of [context, context menu text, id]
var redditURL = 'http://www.reddit.com/submit';
var contexts = [["page", "Submit page", "id-submitPage"], ["link", "Submit link", "id-submitLink"], ["editable", "Submit text", "id-submitText"], ["image", "Submit image", "id-submitImage"]];
// Add all menus to their context
contexts.forEach(function(element) {
chrome.contextMenus.create({
"title" : element[1],
"contexts" : [element[0]],
"id" : element[2]
});
});
// Add actions to menus
chrome.contextMenus.onClicked.addListener(function(info, tab) {
var submittedURL = tab && tab.url;
if (info["menuItemId"] == "id-submitPage") {
chrome.tabs.create({
"url" : redditURL
}, function(tab) {
// After we create the tab we also send a message to the content
// script associated with the page to intercept our info
console.log(submittedURL);
chrome.tabs.sendMessage(tab.id, {
"url" : submittedURL,
"type" : "submitPage"
});
});
}
});
As you can in see in the addListener I am using chrome.tabs.sendMessage to send the URL I am submitting to the content script associated with: redditURL .
The content script: contextMenu-RedditSubmit.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
alert('here');
console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
});
And the manifest file:
...
"background": {
"scripts": ["contextMenu.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["http://www.reddit.com/submit"],
"js": ["contextMenu-RedditSubmit.js"],
"run_at": "document_start"
}
],
...
Problem is my messages are not received inside the contextMenu-RedditSubmit.js content script. I cannot see neither the console.log nor the alert. Any tips ?
Your message is sent before event document_start content scripts execute.
To ensure it works, switch to using programmatic injection:
chrome.tabs.create({
"url" : redditURL
}, function(tab) {
// After we create the tab we also send a message to the content
// script associated with the page to intercept our info
chrome.tabs.executeScript(
tab.id,
{file: "contextMenu-RedditSubmit.js"},
function() {
// Here, it is guaranteed that the script finished executing
// (or there was an error)
chrome.tabs.sendMessage(tab.id, {
"url" : submittedURL,
"type" : "submitPage"
});
}
);
});