JavaScript

[JavaScript]ブラウザバック判定

isBrowserBack(){
    const perfEntries = performance.getEntriesByType("navigation");
    let result = false;
    perfEntries.forEach((perfEntry) => {
        if(perfEntry.type == 'back_forward'){
            result = true;
        }
    });
    return result;
}

[JavaScript]Promise

getCart(){
    return new Promise((resolve,reject) => {
        const url = 'url';
        fetch(url)
            .then((response)=>{
                if (!response.ok) {
                    throw new Error();
                }
                return response.json();
            })
            .then((json)=>{
                resolve(json);
            })
            .catch((error)=>{
                reject(error);
            });
    });
}

this.getCart()
.then((json)=>{
    
})
.catch((error)=>{

});

[JavaScript]文字列から漢字抽出

文字列から漢字抽出

const str = 'ひらがな小林カタカナ漢字';
const pattern = /(\p{scx=Han}+)/ug;
const matches = str.match(pattern);
console.log(matches);

出力

(2) ['小林', '漢字']

[JavaScript]ShopifyCartAPIを叩く(update.js)

let sendData = {
    updates : {}
};
this.deleteItems.forEach((item,index)=>{
    sendData.updates[item.key] = 0;
});
let options = {
    method  : 'POST',
    credentials: 'same-origin',
    headers : {
        'Content-Type': 'application/json'
    },
    body    : JSON.stringify(sendData)
};
fetch(window.Shopify.routes.root+'cart/update.js',options)
.then((response)=>{
    if (!response.ok) {
        throw new Error();
    }
    return response.json;
})
.then((json)=>{
    this.finishFetch(2);
})
.catch((error)=>{
    console.log(error);
});

[JavaScript]ShopifyCartAPIを叩く(change.js)

let sendData = {
    id         : item.key,
    quantity   : item.quantity,
    properties : {}
};
item.properties.forEach((property,index)=>{
    sendData.properties['プロパティ'+(index+1)] = property.value;
});
let options = {
    method       : 'POST',
    credentials  : 'same-origin',
    headers : {
        'Content-Type' : 'application/json'
    },
    body         : JSON.stringify(sendData)
};
fetch(window.Shopify.routes.root+'cart/change.js',options)
.then((response)=>{
    if (!response.ok) {
        throw new Error();
    }
    return response.json;
})
.then((json)=>{
    this.finishFetch();
})
.catch((error)=>{
    console.log(error);
});

[Shopify][JavaScript]住所編集の国で都道府県更新

Liquid(HTML)

国<select name="address[country]" {% if form.country != blank %}data-default-label="{{ form.country }}{% else %}data-default="Japan{% endif %}">{{ country_option_tags }}</select><br>
都道府県<select name="address[province]" data-default-label="{{ form.province }}"></select>

JavaScript

document.querySelectorAll('[name="address[country]"]').forEach((elm,index)=>{
    elm.addEventListener('change',(e)=>{
        onChangeCountry(e);
    });
});
onChangeCountry(e){
    const option = e.target.querySelector('[value="'+e.target.value+'"]');
    const provinceSelect = e.target.form.querySelector('[name="address[province]"]');
    if(option && provinceSelect){
        let options = [];
        const provinces = JSON.parse(option.dataset['provinces']);
        provinces.forEach((province,index)=>{
            options.push('<option value="'+province[0]+'">'+province[1]+'</option>');
        });
        provinceSelect.innerHTML = options.join('');
    }
}

[JavaScript]ファイルサイズ取得

const options = {
   method  : "HEAD"
};
fetch(elm.href,options)
    .then((response)=>{
        if (!response.ok) {
            throw new Error();
        }
        return response;
    })
    .then((response)=>{
        const fileSize = response.headers.get("Content-Length");
        if(fileSize) {
            console.log(fileSize);
        }else{
            throw new Error();
        }
    })
    .catch((error)=>{
    });

[JavaScript]getRGBAByHex

getRGBAByHex(hex,alpha){
    if (hex.slice(0,1) == "#")hex = hex.slice(1) ;
    if (hex.length == 3)hex = hex.slice(0,1) + hex.slice(0,1) + hex.slice(1,2) + hex.slice(1,2) + hex.slice(2,3) + hex.slice(2,3);
    let rgb = [hex.slice(0,2),hex.slice(2,4),hex.slice(4,6)].map(function(str){
        return parseInt(str,16);
    });
    return `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${alpha})`;
}

[JavaScript]canvas.clip

animate() {
    requestAnimationFrame(()=>{
        this.animate();
    });
    const ctx;
    ctx = canvas.getContext('2d');
    ctx.globalCompositeOperation = "source-over";
    ctx.globalAlpha = 1.0;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.beginPath();
    ctx.rect(0,0,canvas.width,100);
    ctx.clip();
    //ここに描画処理
    ctx.restore();
}