Skip to content

Commit

Permalink
#4 Scripts from snippets work correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
edwingamboa committed May 31, 2019
1 parent 0a7e36d commit 31190ea
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions lib/content_script.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,23 @@
`The element to be injected is not a script, instead it is: ${script.tagName}`
);
} else {
let script = document.createElement('script');
if (foreignScript.hasAttributes()) {
let attrs = foreignScript.attributes;
for (let i = attrs.length - 1; i >= 0; i--) {
script.setAttribute(attrs[i].name, attrs[i].value);
}
}
script.innerHTML = foreignScript.innerHTML || '';
document.head.appendChild(script);
document.head.appendChild(cloneElement(foreignScript));
}
}
}

function cloneElement(element) {
let clonedElement = document.createElement(element.tagName);
if (element.hasAttributes()) {
let attrs = element.attributes;
for (let i = attrs.length - 1; i >= 0; i--) {
clonedElement.setAttribute(attrs[i].name, attrs[i].value);
}
}
clonedElement.innerHTML = element.innerHTML || '';
return clonedElement;
}

function injectSnippet(html, containerSelector, position) {
if (!containerSelector) {
containerSelector = DEFAULT_CONTAINER_SELECTOR;
Expand All @@ -67,20 +71,19 @@
container = document.querySelector(DEFAULT_CONTAINER_SELECTOR);
}
let snippets = htmlToElements(html);
for (let i = snippets.length; i > 0; i--) {
for (let i = 0; i < snippets.length; i++) {
switch (position) {
case 'beginning':
container.insertBefore(snippets[snippets.length - 1], container.firstChild)
container.insertBefore(cloneElement(snippets[snippets.length - (i + 1)]), container.firstChild)
break;
case 'beforeSelected':
container.before(snippets[0]);
break;

container.before(cloneElement(snippets[i]));
break;
case 'afterSelected':
container.after(snippets[snippets.length - 1]);
container.after(cloneElement(snippets[snippets.length - (i + 1)]));
break;
default:
container.appendChild(snippets[0]);
container.appendChild(cloneElement(snippets[i]));
break;
}
}
Expand Down

0 comments on commit 31190ea

Please sign in to comment.