mmmh
mmmh

Reputation: 167

simple option script for chrome

I'm trying to made a options site for my Chrome Extension. I want just that if checkbox 1 is enable script is runs etc... I searched around but I found only outdated threads for this topic. This is the manifest.json from my extension:

{
  "name": "My First Extension",
  "version": "1.0",
  "manifest_version": 2,
  "options_page": "options.html",
  "description": "The first extension that I made.",
  "content_scripts": [
    {
      "matches": ["http://*.example.com/*"],
      "all_frames": true,
      "js": ["script1.js", "script2.js"]
    }
  ],
  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": [
    "tabs", "http://*.example.com/*"
  ]
}

The options.html:

<!DOCTYPE html>
<html>
<body class="uber-frame" i18n-values=".style.fontFamily:fontfamily;.style.fontSize:fontsize" style="font-family: &#39;Segoe UI&#39;, Tahoma, sans-serif; font-size: 125%">
<div id="main-content" align="center">
  <div id="mainview">
    <section id="scripts">
<h3>Scripts</h3>
      <label>
        <input type="checkbox" class=script1 >
        <span>Enable Script 1</span>
     </label>
    <div>
     <label>
        <input type="checkbox" class=script2>
        <span>Enable Script 2</span>
     </label>
    </div>
    </section>
  </div>
</div>
</body></html>

I don' t know how can i say the extension wich script shout be activ and which not. I think I need a other script to get the values from the classes of the checkboxes and probably I should set the content scripts to backgrond scripts. Would be great if someone could help me.

Upvotes: 0

Views: 262

Answers (1)

Okan Kocyigit
Okan Kocyigit

Reputation: 13421

Update:

I've updated all codes for make both script run at the same time.

OK, at first you should save options data in localstorage, so you can access data from all pages. that makes your job easy.

For manipulating data I've created a javascript file named as global.js.

This file must be included at the start of options.html and content.js manually or in manifest.json.

global.js

var localStoragePrefix = "myextension_";
var LS_options  = localStoragePrefix + "options";
var Options = {
    Scripts : [
        {
            name : "script 1",
            path : "script1.js",
            enable : false
        },
        {
            name : "script 2",
            path : "script2.js",
            enable : false
        }
    ]
};

function DB_setValue(name, value, callback) {
    var obj = {};
    obj[name] = value;
    console.log("ayarlar kaydedildi");
    console.log(obj);
    chrome.storage.local.set(obj, function() {
        if(callback) callback();
    });
}

function DB_load(callback) {
    chrome.storage.local.get(LS_options, function(r) {
        if ($.isEmptyObject(r[LS_options])) {
            DB_setValue(LS_options, Options, callback);
        } else {
            Options = r[LS_options];
            callback();
        }
    });
}

function DB_save(callback) {
    DB_setValue(LS_options, Options, function() {
        if(callback) callback();
    });
}

function DB_clear(callback) {
    chrome.storage.local.remove(LS_options, function() {
        if(callback) callback();
    });
}

And here is the updated options.html, you will see some js files included.

  • jquery.min.js (You don't need to use this, I just want to make it more useful)
  • global.js
  • options.js

options.html

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript" src="globals.js"></script>
  <script type="text/javascript" src="options.js"></script>
</head>
<body class="uber-frame" i18n-values=".style.fontFamily:fontfamily;.style.fontSize:fontsize" style="font-family: &#39;Segoe UI&#39;, Tahoma, sans-serif; font-size: 125%">
<div id="main-content" align="center">
  <div id="mainview">
    <section id="scripts">
      <h3>Scripts</h3>
      <div id="scriptTemplate" style="display:none">
       <label>
          <input type="checkbox" data-script = "script.js" />
          <span>Enable Script</span>
       </label>
      </div>
    </section>
  </div>
</div>
</body>
</html>

Event handler attachments are in options.js file.

options.js

$(function(){ DB_load(startOptionsPage); });

function startOptionsPage() {

    $.each(Options.Scripts, function(index, script) {
       var $scriptTemplate = $("#scriptTemplate").clone().show();
       $scriptTemplate.find("label span").html("Enable " + script.name);

       $scriptTemplate.find("label input[type='checkbox']")
       .data("script", script.path)
       .click(function() {
          if ($(this).is(":checked")) {
              script.enable = true; 
          } else {
              script.enable = false;
          }
          DB_save(function() {
              console.log("DB saved");
          });
       })
       .prop('checked', script.enable);

       $("#scripts").append($scriptTemplate);
    });    
}

And in content.js file we are getting Options and including the script if there is a selected one.

content.js

DB_load(function() {    
    $.each(Options.Scripts, function(index, script) {
        if (script.enable) {
            $.getScript(chrome.extension.getURL(script.path), function() {
                console.log(script.name + " was loaded!");
            });
        }
    });
});

script1.js

alert("Hello from script1");

script2.js

alert("Hello from script2");

For all of this you should update the manifest.json file.

  • including global.js into the content_script
  • permission for localstorage
  • including web_accessible_resources for script1.js and script2.js (Why?)

Finally here is the updated manifest.json

manifest.json

{
  "name": "My First Extension",
  "version": "1.0",
  "manifest_version": 2,
  "options_page": "options.html",
  "description": "The first extension that I made.",
  "content_scripts": [
    {
      "matches": ["http://stackoverflow.com/*"],
      "all_frames": true,
      "js": ["jquery.min.js","globals.js","content.js"],
      "run_at": "document_end"
    }
  ],
  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": [
    "tabs", "http://stackoverflow.com/*", "storage"
  ],
   "web_accessible_resources": [
    "script1.js",
    "script2.js"
  ]
}

Your script folder should be like this,

enter image description here

How can I add more scripts?

There are only two changes you must make,

You will add script to main folder like the other script1.js and script2.js, and also you will add it to web_accessible_resources into the manifest.json.

You will also update "global.js", just add new script object to Options.Scripts array. like this.

var Options = {
    Scripts : [
        {
            name : "script 1",
            path : "script1.js",
            enable : false
        },
        {
            name : "script 2",
            path : "script2.js",
            enable : false
        },
        {
            name : "script 3",
            path : "script3.js",
            enable : false
        }
    ]
};

That's all. But don't forget to remove extension from chrome before you load the new updated one, because old options will stay there, and that won't work as you expect if don't do that.

Upvotes: 1

Related Questions