Chrome extension: Content script matching URL pattern for Gmail message

自闭症网瘾萝莉.ら 提交于 2019-12-21 22:50:33

问题


For my Chrome extension, I need a matching pattern for any valid Gmail message URL. Example:

https://mail.google.com/mail/u/0/?shva=1#inbox/140acd877b64109b

What I tried in manifest.json is the following:

"content_scripts": [ {
        "matches":      ["*://*.mail.google.com/mail/u/0/?shva=1#inbox/*"],
        "css":          ["default.css"]
    } ]

However, my custom stylesheet is not applied when I access a Gmail message with the URL pattern above.

Any ideas why it is not applied?

If I only use "matches": ["*://*.mail.google.com"], then it works. Yet I do not want the stylesheet to be applied to my inbox page too. Thus I am looking for a pattern to only catch single message pages.


回答1:


The location fragment (#...) is always ignored in the match pattern. Last time I checked, the query string is also ignored for the "css" field.

To get the desired effect, just insert the stylesheet on "*://*.mail.google.com/*", and use a content script to detect URL changes. For example:

Fragment of manifest.json:

"content_scripts": [ {
    "matches":      ["*://*.mail.google.com/*"],
    "css":          ["default.css"],
    "js":           ["style-toggler.js"]
} ]

Example of default.css:

.turn-on-my-style img {
    visibility: hidden;
}

If prefixing your CSS selectors takes too much efforts, I suggest to use a CSS preprocessor like LESS.

style-toggler.js:

function hashCheck() {
    if (/^#inbox\/.*/.test(location.hash)) {
        document.documentElement.classList.add('turn-on-my-style');
    } else {
        document.documentElement.classList.remove('turn-on-my-style');
    }
}
window.addEventListener('hashchange', hashCheck);
hashCheck();


来源:https://stackoverflow.com/questions/18419481/chrome-extension-content-script-matching-url-pattern-for-gmail-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!