Two scripts for two diff sites

Forums » Dev.Opera » Opera Extensions Development Discussions

You need to be logged in to post in the forums. If you do not have an account, please sign up first.

Go to last post

1. July 2012, 06:59:09

beBoss

Posts: 16

Two scripts for two diff sites

I have two scripts which are for two different sites. How to create extension which have button and there in settings to have two check boxes for on/off the scripts.
Site 1, script 1
(function () {
        var
                links   = document.getElementsByTagName( 'a' ),
                i               = links.length,
                href;

        while( i-- ) {
                href = links[i].getAttribute( 'href' );

                if( href.indexOf( 'javascript:decision' ) > -1 )
                        links[i].setAttribute( 'href', href.indexOf( ",'" ) + 2, href.indexOf( "')" ) );
        }
})();


Site 2, script 2
(function () {
        var
                links   = document.getElementsByTagName( 'a' ),
                i               = links.length,
                evt;

        while( i-- ) {
                if( links[i].getAttribute( 'href' ) == 'javascript: void(0);' ) {
                        evt = links[i].getAttribute( 'onclick' ).match( /location\.href = '(.+?)';/ );

                        if( evt[1] ) {
                                links[i].setAttribute( 'href', evt[1] );
                                links[i].onclick = null;
                        }
                }
        }
})();


if (page = site 1) and (script1 = on) then script 1 do his job, etc

2. July 2012, 23:33:12

spadija

Posts: 1636

Use widget.preferences to store the settings. Then, just read the settings from widget.preferences in your injected scripts.

3. July 2012, 00:26:35

beBoss

Posts: 16

Well i saved settings with this func:
function savePrefs () {
  for (var i = 0; i < fields.length; i++) {
    var field = fields[i];
    widget.preferences.setItem(field.name, field.value);
  }
}


but I don't know how to read the settings. And after reading the settings if checkbox1 is unchecked how to stop injected script.
I created two injected scripts for the two sites. So if checkbox1(site) is uncheck site1.js have to stop working, but how? smile

4. July 2012, 01:45:59

spadija

Posts: 1636

Use widget.preferences.getItem() to retrieve the saved values.

4. July 2012, 10:20:59

beBoss

Posts: 16

Well, I need a little help with this, here are my scripts and codes:

Injected scripts (includes folder):

ArenaBG.js
// ==UserScript==
// @author 	beBoss 
// @name 	Remove ArenaBG Adult Content
// @include http://arenabg.com/torrents/*
// @include http://www.arenabg.com/torrents/*
// ==/UserScript=

window.addEventListener('DOMContentLoaded', function() {
	if( widget.preferences.getItem("ArenaBG") == true ) {
		var
				links   = document.getElementsByTagName( 'a' ),
				i               = links.length,
				evt;

		while( i-- ) {
				if( links[i].getAttribute( 'href' ) == 'javascript: void(0);' ) {
						evt = links[i].getAttribute( 'onclick' ).match( /location\.href = '(.+?)';/ );

						if( evt[1] ) {
								links[i].setAttribute( 'href', evt[1] );
								links[i].onclick = null;
						}
				}
		};
	}		
}, false);


Zamunda.js
// ==UserScript==
// @author 	beBoss 
// @name 	Remove Zamunda Adult Content
// @include	http://zamunda.net*
// ==/UserScript=

window.addEventListener('DOMContentLoaded', function() {
	if( widget.preferences.getItem("Zamunda") == true ) {
		var
				links   = document.getElementsByTagName( 'a' ),
				i               = links.length,
				href;

		while( i-- ) {
				href = links[i].getAttribute( 'href' );

				if( href.indexOf( 'javascript:decision' ) > -1 )
						links[i].href = links[i].href.substring( links[i].href.indexOf(',\'') + 2, links[i].href.indexOf('\')') );
		};
	}
}, false);


Extension files:
background.js
// background.js
// Add a button to Opera's toolbar when the extension loads.
window.addEventListener("load", function() {
  // Buttons are members of the UIItem family.
  // Firstly we set some properties to apply to the button.
  var UIItemProperties = {
    disabled: false, // The button is enabled.
    title: "BGTrackers Adult Remover", // The tooltip title.
    icon: "icon_18.png", // The icon (18x18) to use for the button.
    popup: {
      href: "settings.html",
      width: "500px",
      height: "500px"
    }
  };

  // Next, we create the button and apply the above properties.
  var button = opera.contexts.toolbar.createItem(UIItemProperties);
  // Finally, we add the button to the toolbar.
  opera.contexts.toolbar.addItem(button);
}, false);


settings.html

<!DOCTYPE html>
<html>
<head>
<title>BGtrackers Adult Settings</title>
</head>
<script>
var form   = document.getElementById("settings-form");
var fields = form.querySelectorAll("input[type='checkbox']");

// Set the preference values for each field
function saveSettings () {
  for (var i = 0; i < fields.length; i++) {
    var field = fields[i];
    widget.preferences.setItem(field.name, field.value);
  }
}
</script>
<body>
	<fieldset id="settings-form">
		<legend>Options</legend>
		<label>ArenaBG:	<input name="cbArenaBG" value="ArenaBG" type="checkbox" checked="checked"></label>

		<label>Zamunda:	<input name="cbZamunda" value="Zamunda" type="checkbox" checked="checked"></label>

		<input type="button" value="Save" onclick="saveSettings()"/>
	</fieldset>
</body>
</html>


I hope it needs a little changes to gets working smile

4. July 2012, 16:47:24

spadija

Posts: 1636

Okay, a couple things to fix:

For checkboxes, "value" will always be the text you used in the <input> tag's value attribute. Instead, use the "checked" attribute, which is true/false depending on whether the box is checked.

Your <input> elements are named "cbArenaBG" and "cbZamunda", and you are saving their values using their names as a key, so you need to use the same keys when retrieving the values. Also, when you save things to widget.preferences, they get changed to a string. This means, when you save a boolean "true", then retrieve it, you get the string "true". Boolean "true" and string "true" aren't equal to each other, so your test is always going to return false and the script will never run.
>>> true == "true"
false

Instead of testing against boolean "true", just test against the string, "true". Alternatively, you could use JSON.parse() to convert the string to a boolean:
if(widget.preferences.getItem('cbArenaBG') == 'true') { ...
// or
if (JSON.parse(widget.preferences.getItem('cbArenaBG')) = true) { ...


If you use Dragonfly, (Ctrl+Shift+I to open/close it) you can see everything in widget.preferences from the "Storage" tab, and you can quickly test code using the "Console" tab. I find it very helpful when debugging extensions.

One more suggestion: If you name your settings page "options.html", Opera will use it as the preferences page for your extension. Using a popup purely for extension settings just wastes toolbar space with a button you rarely use, so unless you think it is necessary to be able to access those settings quickly and often, I would suggest using a preferences page instead of a popup.

4. July 2012, 20:56:53

beBoss

Posts: 16

Thanks for the info and your time, but I think I can't do it. It's not in my abilities smile

5. July 2012, 03:45:55

spadija

Posts: 1636

Judging from how close you are, it's certainly not beyond your abilities. This is all you should need to change:

change field.value to field.checked
// Set the preference values for each field
function saveSettings () {
  for (var i = 0; i < fields.length; i++) {
    var field = fields[i];
    widget.preferences.setItem(field.name, field.checked);
  }
}


Retrieve the value of "cbArenaBG" instead of "ArenaBG" (since you saved it with the name of your <input>, and that was named "cbArenaBG") and check it against "true" instead of true, since widget.preferences saves things as strings.
// ==UserScript==
// @author 	beBoss 
// @name 	Remove ArenaBG Adult Content
// @include http://arenabg.com/torrents/*
// @include http://www.arenabg.com/torrents/*
// ==/UserScript=

window.addEventListener('DOMContentLoaded', function() {
	if( widget.preferences.getItem("cbArenaBG") == "true" ) { ... 


Same thing as above.
// ==UserScript==
// @author 	beBoss 
// @name 	Remove Zamunda Adult Content
// @include	http://zamunda.net*
// ==/UserScript=

window.addEventListener('DOMContentLoaded', function() {
	if( widget.preferences.getItem("cbZamunda") == "true" ) { ...

5. July 2012, 05:56:20

beBoss

Posts: 16

Well I know I'm close, but I tried this, and popup doesn`t save (maybe) values.
After closing and reopen the popup checkboxes are always checked, because of this:
checked="checked"


In Widget Preferences there is nothing (I clicked 'update' button).
So I have to add two things:
1. Popup has to get current state of checkboxes (checked or not) onload
2. maybe save function doesn`t work ?

5. July 2012, 22:29:01

spadija

Posts: 1636

Ah, right. Two ways you could handle that:

1. Remove the checked="checked" from each <input> element, then add some code to initialize the checkboxes when the page loads:
function loadSettings() {
  for (var i = 0; i < fields.length; i++) {
    var field = fields[i];
    if (widget.preferences.getItem(field.name, field.checked) == 'true')
      field.checked = true;
  }
}

window.addEventListener('DOMContentLoaded', loadSettings, false);


2. Use my OperaExtOptions library, which handles all the dirty work of reading and saving settings in the options page so you don't have to. (It uses field names just like you are using, so your injected script code shouldn't be any different with either method.)

Also, one more thing that could be causing problems: run this part of your options page...
var form   = document.getElementById("settings-form");
var fields = form.querySelectorAll("input[type='checkbox']");

...on DOMContentLoaded. It is getting executed before the page loads, which likely means form is null and fields is an empty array. You can keep the code in the same place so long as you tell Opera to run it once the DOM is loaded, like so:
window.addEventListener('DOMContentLoaded', function() {
  var form   = document.getElementById("settings-form");
  var fields = form.querySelectorAll("input[type='checkbox']");
}, false);

5. July 2012, 23:24:09

beBoss

Posts: 16

Well I tried first way to fix my code, but no luck there. So, now I'm using you library and it is perfect smile
Thanks for your help and time. If i have any question I will be here p

6. July 2012, 16:05:36

beBoss

Posts: 16

Hey one more question,

how to close popup if it lose focus ?
I tried something like this:
	<script>
		OptionsPage.init(storage);
		window.addEventListener( "load", function(){
			if( opera.extension.windows )
			{
				opera.extension.windows.onblur = function( event ){
						window.close();
				}
			} else {
				// couldn't find an opera.extension.windows object.
			}
		}, false);
	</script>
</head>


but doesn't seems to work.

7. July 2012, 02:06:46

spadija

Posts: 1636

The popup doesn't close when it loses focus so that you can debug it with Dragonfly. When you build an .oex and install the extension with it, (not developer mode) it will close like normal.

Forums » Dev.Opera » Opera Extensions Development Discussions