Establish A Communication Link Between Content Script And Background Page
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 usin
Solution 1:
A few major issues:
- You're depending on some element on the page having the ID
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
). - What does "the extension button" mean? If it means a browser action, that's a part of your extension, so you're correct in wanted to send something from the background script. This is also an easier case, as it's probable that (aside from the issue above of no Google pages having an element of ID
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});
});
Post a Comment for "Establish A Communication Link Between Content Script And Background Page"