I am looking to create an extension for a particular site to provide additional formatting and sharing options that they don’t currently have.
I am having issues getting things to communicate properly and there doesn’t seem to be a clearly laid out example.
Manifest:
{
"name": "Test",
"description": "Testing.",
"version": "1.0",
"background_page": "background.html",
"permissions": [
"tabs", "http://www.sitedomain.com/*"
],
"content_scripts": [
{
"matches": ["*://*.sitedomain.com/*"],
"js": ["jquery.min.js", "test.js"],
"css": ["test.css"]
}
]
}
Content Script:
$(document).ready(function () {
alert('test js fired');
$("#ColumnContainer div.item").each(function () {
$(this).css("background-color", "skyBlue");
var itemId = $(this).children("a.itemImage").attr("href");
$(this).children(".details").append("<a href=\"javscript:void(false);\" onclick=\"gotoItem('" + itemId + "');\">Goto Item</a>");
});
});
chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
alert('listener request');
alert(request);
});
JavaScript of Background HTML:
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == "complete") {
if (tab.url.indexOf("sitedomain.com") > -1) {
chrome.tabs.executeScript(null, {file: "test.js"});
}
}
});
chrome.tabs.sendRequest(tabId, request, responseCallback);
function responseCallback() {
alert('response callback');
}
function gotoItem(itemId) {
alert('goto Item - ' + itemId);
}
The above code does append the link and change the styling on the client page when the sitedomain.com is loaded. However, I haven’t had any luck getting the gotoItem method to fire, Chrome Dev Tools shows undefined. I have tried various combinations, but just can’t quite grasp the listeners and requests yet.
I would really like to see a clean sample that just shows how to call a method from each site.
I see two issues with your code. 1) the
gotoItemfunction is defined in the background page andcontent_scriptscan’t access functions there. 2)content_scriptsand javascript on pages they are injected into can not interact so youronclickcan’t be part of the links html.To fix #1 is as simple as moving the
gotoItemfunction to be in thecontent_script.To fix #2 something like the following should work.
You may have to modify how
itemIdgets passed.