Try this code for _OnClick function:
_OnClick: function ($this, $widget, eventName) {
var $parent = $this.parents('.' + $widget.options.classes.attributeClass),
$wrapper = $this.parents('.' + $widget.options.classes.attributeOptionsWrapper),
$label = $parent.find('.' + $widget.options.classes.attributeSelectedOptionLabelClass),
attributeId = $parent.attr('attribute-id'),
$input = $parent.find('.' + $widget.options.classes.attributeInput);
//console.log($parent);
//window.location.hash = '?size='+size+'&color='+color;
if ($widget.inProductList) {
$input = $widget.productForm.find(
'.' + $widget.options.classes.attributeInput + '[name="super_attribute[' + attributeId + ']"]'
);
}
if ($this.hasClass('disabled')) {
return;
}
if ($this.hasClass('selected')) {
$parent.removeAttr('option-selected').find('.selected').removeClass('selected');
$input.val('');
$label.text('');
$this.attr('aria-checked', false);
} else {
$parent.attr('option-selected', $this.attr('option-id')).find('.selected').removeClass('selected');
$label.text($this.attr('option-label'));
$input.val($this.attr('option-id'));
$input.attr('data-attr-name', this._getAttributeCodeById(attributeId));
$this.addClass('selected');
$widget._toggleCheckedAttributes($this, $wrapper);
}
$widget._Rebuild();
if ($widget.element.parents($widget.options.selectorProduct)
.find(this.options.selectorProductPrice).is(':data(mage-priceBox)')
) {
$widget._UpdatePrice();
}
$widget._loadMedia(eventName);
$input.trigger('change');
var i =0;
var hashUrl = '';
$('.swatch-attribute[option-selected]').each(function(index){
if(i > 0) hashUrl+= '&';
hashUrl+=$(this).attr('attribute-code')+'='+$(this).attr('option-selected');
i++;
});
if(hashUrl) window.location.hash = '?'+hashUrl;
},
Magento2 already have an option to select it by attribute code and option Id. You can also see the function _EmulateSelected where it triggers click for each selected options.
You can also check the function _EmulateSelected from where it check the parameters from the url and return the selected options with attribute code to the function _RenderControls. In the function _RenderControls you can find the line $widget._EmulateSelected($widget._getSelectedAttributes());
at the end of the function which tells that options are selected.
The code is not tested but it should works.