Murat Dikmen
Murat Dikmen

Reputation: 23

Chrome Extension doesn't inject content script after redirect

I am developing a Chrome Extension that interacts with Twitter and injects a content script when the user visits twitter.com/home. I declared content_scripts in manifest.json and everything works fine on twitter.com/home. However, when I visit twitter.com it redirects to twitter.com/home and the extension does not inject the content script. Adding "twitter.com" to the "matches" list in manifest.json solves the problem but I want the extension to inject the script only when twitter.com/home loads. I am considering using webNavigation API to detect redirects but I wonder if there are more efficient ways to achieve this. Thanks!

manifest.json

  "name": "xxx",
  "version": "1.0",
  "description": "abc",
  "permissions": [
    "activeTab",
    "declarativeContent",
    "storage"
  ],
  "content_scripts": [
    {
      "matches": ["https://twitter.com/home", "https://twitter.com/"],
      "run_at": "document_idle",
      "js": ["script.js"]
    }
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "manifest_version": 2
}

Upvotes: 2

Views: 1169

Answers (1)

Hank X
Hank X

Reputation: 2054

Twitter is loading the page via ajax, not page reloading. thus, when you click items on the page, page content changed, URL changed. but the page actually does not reload, that's why your content scripts not working.

do this: change your matches to https://twitter.com/*. this will make the content scripts injects to all twitter pages.

in your content script script.js, you need to add some logic to detect if the user is on the home page. since the page is not reloading, you need to use something like MutationObserver to detect page content changing(like if the home link is highlighted). so that your script knows the current page is home page and does something you want to do.

Upvotes: 6

Related Questions