Created
November 27, 2017 12:59
-
-
Save Akiyamka/06fbf6d10601f6b0c5d5ba56bc0ca956 to your computer and use it in GitHub Desktop.
Apply custom js and css
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
applyCssJs({ data }) { | |
let head = document.querySelector('head'); | |
if (data && data.css) { | |
head.innerHTML += `<style rel="stylesheet" type="text/css"/>${data.css_value}</style>`; | |
} | |
if (data && data.favicon) { | |
let icon = document.querySelector('[rel="shortcut icon"]'); | |
icon.href = data.favicon; | |
} | |
if (data && data.external_js) { | |
let scripts = data.external_js.trim().split('<script>'); | |
scripts = scripts.map(script => script.split('</script>')[0]).join(); | |
let links = []; | |
let myArray; | |
let re = /src=".+?"/g; | |
// From MDN example (RegExp/exec) | |
while ((myArray = re.exec(data.external_js)) !== null) { // eslint-disable-line no-cond-assign | |
links.push(myArray[0].slice(5, -1)); | |
} | |
if (scripts) { | |
runScript.call(window, scripts); | |
} | |
if (links.length > 0) { | |
links.forEach((link) => { | |
let tag = document.createElement('script'); | |
tag.setAttribute('src', link); | |
document.head.appendChild(tag); | |
}); | |
} | |
} | |
function runScript(script) { | |
try { | |
eval(script); | |
} catch (error) { | |
console.warn('Error when try run user script'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment