Question

I'm trying to write a trivial Chrome pageAction extension to change all anchors on a page from one domain to another... but I can't quite seem to get it to work, and I'm having trouble debugging it.

Am I misunderstanding how this kind of extension needs to be built? Or am I just misusing the API?

manifest.json:

{
  "name": "theirs2ours",
  "version": "1.0",
  "description": "Changes all 'their' URLs to 'our' URLs.",
  "background_page": "background.html",
  "permissions": [
    "tabs"
  ],
  "page_action": {
    "default_icon": "cookie.png",
    "default_title": "theirs2ours"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["content.js"]
    }
  ]
}

background.html:

<html>
<head>
<script type='text/javascript'>

chrome.tabs.onSelectionChanged.addListener(function(tabId) {
  chrome.pageAction.show(tabId);
});

chrome.tabs.getSelected(null, function(tab) {
  chrome.pageAction.show(tab.id);
});

chrome.pageAction.onClicked.addListener(function(tab) {
    chrome.tabs.sendRequest(tab.id, {}, null);
});

</script>
</head>
<body>
</body>
</html>

content.js:

var transform = function() {
  var theirs = 'http://www.yourdomain.com';
  var ours = 'http://sf.ourdomain.com';
  var anchors = document.getElementsByTagName('a');
  for (var a in anchors) {
    var link = anchors[a];
    var href = link.href;
    if (href.indexOf('/') == 0) link.href = ours + href;
    else if (href.indexOf(theirs) == 0) link.href = href.replace(theirs, ours);
  }
};

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  transform();
});
Was it helpful?

Solution

You're not requesting permission to run content scripts on these pages. The matches for content scripts determines what pages they are executed in but you still need to request permission to inject scripts in to these pages.

"permissions": [
  "tabs",
  "http://*/*"
]

OTHER TIPS

I think this is not the way to do the extension you want.

First of all, I assume you want to replace the anchors when you click the page action button.

The manifest you have injects content.js on every page, no matter if you click or not the page action button.

I suggest you remove the content_scripts field from your manifest, and inject content.js manually, with

chrome.tabs.executeScript(tabId, {file:'content.js'})

You should do this in the page action's click listener.

By the way, in that listener you are sending a request to the content script, but it hasn't a listener to listen to such request message. In this extension you won't need to use senRequest.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top