Reputation: 1737
Developing a chrome extension using javascript is one of my university projects.
I don't know how to establish a communication link between content script and background page using messaging. I need some help in this establishing the connection
background.html
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getHTML"}, function(response) {
console.log(response.data);
});
});
content_script.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getHTML")
sendResponse({data: document.getElementById('header').innerHTML});
else sendResponse({});
});
Upvotes: 0
Views: 3986
Reputation: 7663
A few major issues:
header
. Such IDs are at the discretion of the site designer, so very few pages actually do have that (including Google). Maybe go for something a little more universal, like the title of the page (document.title
).header
), you're just not capturing the browser action click event. If it's some injected button, however, it's the other way around.What you want (browser action version)
background.html (inline):
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, { method: "getHTML"}, function(response) {
console.log(response.data);
});
});
});
content_script.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method === "getHTML") {
sendResponse({data: document.title});
} else {
sendResponse({});
}
});
What you might want (injected button click version)
background.html:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method === "getHTML") {
console.log(request.data);
}
});
content_script.js:
function buttonClick() {
chrome.extension.sendRequest({method: "getHTML", data: document.title});
}
Code for response to comment below
Very important recommendation: Chrome's developer reference is probably one of the friendliest out there. If you want to know what parts of the chrome.*
API are available, start there.
function getHtml(tabId) {
chrome.tabs.sendRequest(tabId, { method: "getHTML"}, function(response) {
console.log(response.data);
});
}
// Note that this will only work once a tab has loaded
chrome.tabs.onSelectionChanged.addListener(function(tabId) {
getHtml(tabId);
});
// This fires the first time a page is loaded
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
if (changeInfo.status === "complete") {
getHtml(tabId);
}
});
Code for second response to comment below
background.html
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method === "getHTML") {
console.log(request.data);
}
});
content_script.js
document.addEventListener("keypress", function(e) {
chrome.extension.sendRequest({method: "getHTML", data: e.which});
});
Upvotes: 6