change color of element Chrome extension

ⅰ亾dé卋堺 提交于 2020-01-15 07:07:27

问题


I have created a simple Jquery script as an chrome extension that are suppose to change the font color of a class.

the script is working fine if I use it directly in the console. but if I run it as an extension It wont trigger when the value is higher than one.

Any suggestion of what could be the problem?

Script.js

 (function(){
         $("#ID-layout-1435216276773-counterValue").each(function() {
                var el = $(this);
                var value = parseFloat(el.text());
                if (value > 1) {
                    el
                        .css("font-weight", "bold")
                        .css("color", "red");

                } else {
                    el.css("font-weight", "normal");
                }
            });   

          })();

Manifest

{
"update_url": "https://clients2.google.com/service/update2/crx",

    "name": "Live",
    "version": "0.3",
    "description": "Live",
    "permissions": [
    "tabs","<all_urls>"
    ],
    "browser_action": {
    "default_icon": "icon.png"
    },
    "icons": { 
                "16": "icon.png",
                "48": "icon.png",
                "128": "icon_128.png" 
            },
    "content_scripts": [
        {
        "matches": [
                "https://www.google.com/analytics/web/?hl=en#dashboard/6I8yfVs_TqSQ_b1tOJYR0Q/a8398197w15972131p74378741/*"
            ],
        "run_at": "document_end" ,
        "js": ["script.js"]     
        }
    ], 
    "manifest_version":2
}

回答1:


You have not actually included jQuery in your content script.

Because content scripts run in isolation from the page, it does not matter whether the page itself has jQuery already included. Your script's context does not have it.

However, your code works from the console, because the code is, by default, executed in the page's context (see that <top frame> selector above the console?), which may have jQuery already. Add to that the fact that Chrome console provides a special version of $ to use in the console, even if there is no jQuery (in which case it's an alias for document.querySelector).

To see what's happening if you execute the code in the extension's context, you need to switch to its context (which is created after you inject something).

You need to add jQuery to your extension's files and inject it before your main script:

"content_scripts": [{
    "matches": [
       ...
    ],
    "run_at": "document_end" ,
    "js": ["jquery.min.js", "script.js"]     
}],


来源:https://stackoverflow.com/questions/31383418/change-color-of-element-chrome-extension

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