如何根据复选框的值使Chrome扩展程序仅在特定网站上起作用

时间:2019-01-10 10:21:24

标签: javascript google-chrome-extension

在我的Chrome扩展程序中,我有2个复选框。如果选择了第一个,则应在google.com域上运行。如果选择了第二个,则它在其他任何地方也应起作用。但是现在,我不知道如何在代码中实现它,因此,如果您仅选择第一个,则扩展名将仅在google.com域上运行。

这是我的contentScript

// getting value from chrome storage
chrome.storage.sync.get(["value"], function(result) {

var links = document.querySelectorAll("link[rel]");
var as = document.querySelectorAll("a[href]"); //doplnit i kdyby nebyl odkaz na a ale například button
var color = "red";

// on the beggining, the result.value is empty, because nobody clicked on confirm in settings
if(result.value != null){
    color = result.value;
}

for (var i = 0, len = links && links.length; i < len; ++i)
{
  var link = links[i];
  var a = as[i];

  if (link.rel == "prerender")
  {
    chrome.runtime.sendMessage({ "newIconPath" : "48.png" });

    var prerendered_href = link.href; 

    for (var j = 0, len = as && as.length; j < len; ++j)
    {
        var a = as[j];
        if(a != "")
        {
            if(extractURL(prerendered_href) == extractURL(a.href)){

                    a.setAttribute("style", "border: 1.5px dashed "+ color +"; display: inline-block !important;");
            }
        }
    }   

  }
  else{
    chrome.runtime.sendMessage({ "newIconPath" : "48-gray.png" });
  }
}   



function extractURL(Adress){
    var pathname = new URL(Adress).pathname;
    var domain = new URL(Adress).hostname.replace("www.","");

    return domain+pathname;
}

});

这是我的background.js

    // Listen to messages from the payload.js script and write to popout.html
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        // read `newIconPath` from request and read `tab.id` from sender
        chrome.browserAction.setIcon({
            path: request.newIconPath,
            tabId: sender.tab.id
        });
    });

// Inject the payload.js script into the current tab after the popout has loaded
window.addEventListener('load', function (evt) {
    chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
        file: 'payload.js'
    });;
});


// Listen to messages from the payload.js script and write to popout.html
chrome.runtime.onMessage.addListener(function (message) {
    document.getElementById('pagetitle').innerHTML = message;
});

document.addEventListener('DOMContentLoaded', function() {
    var c = document.getElementById('button_confirm');
    var ic = document.getElementById('input_color');

    c.addEventListener('click', function() {

        chrome.storage.sync.set({"value": ic.value}, function() {
        console.log("The value stored was: " + ic.value);
        window.close();
    });

    });
});

该复选框位于html文件中。如果选中了第一个复选框,是否有办法使扩展程序仅在Google上运行?

0 个答案:

没有答案