chrome extension with html에 해당하는 글 1

크롬 익스텐션에 vuejs 사용하기 (development of chrome extension with vuejs)

Computer 관심|2018. 5. 4. 14:06
반응형

content script를 사용해서 뭘 만들라 할때 html을 순수 자바스크립트로 만드는건 너무 귀찮은 일이다.


이걸 어떻게 해야 할까.....하다가 vuejs와 html 템플릿을 사용하면 어떻까 싶었고!  삽질을 했다.

먼저 매니페스트 파일을 이렇게 수정하였다.


manifest.json

{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"manifest_version": 2,
"content_scripts":[
{
"matches": ["https://www.google.com/*"],
"js": ["vue.js","contentScript.js"]
}
],
"web_accessible_resources": ["template.html"]
}


여길 보면 js에 vue.js 스크립트를 넣어서 Vue객체를 받을 수 있도록 하였다. 또 템플릿을 추가 하기 위해 web_accessible_resources 를 추가한걸 볼 수 있다.

그 템플릿 파일을 보면


template.html


{{ message }}



contentScript.js

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var div = document.createElement('div');
div.setAttribute("id", "app")
div.innerHTML = this.responseText;
document.body.insertBefore(div, document.body.firstChild);
} else {
console.log('files not found');
}
};
xhttp.open("GET", chrome.extension.getURL("/template.html"), true);
xhttp.send();


setTimeout(function(){
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
}, 100);


비동기 요청을 한뒤에 템플릿을 body 안에 추가한다. 그런데 비동기 요청이 시간이 더 오래걸리기 때문에 vue 객체를 생성할때 setTimeout을 주어서 템플릿이 바디에 먼저 들어간뒤 뷰객체가 생성되도록 하였다.  프로미스로 해볼려 했는데 ㅠㅠ 잘 안됬다 (내가 못해서 그런듯)



더 좋은 방법 있으면 알려주시면 감사하겠습니다.



반응형

댓글()