2014-09-16 4 views
0

순수한 자바 스크립트로 Chrome 확장 프로그램을 작성하여 노드 모음을 가져 와서 일부 변경했습니다.Chrome 확장 자바 스크립트가 제대로 작동하지 않음

var list = document.getElementsByClassName("testclass");  
console.log(list);   //1 
console.log(list.length); //2 
console.log(list[0]);  //3 

이의 출력으로 온다 : 그래서, 진형

1. HTMLCollection object with all elements and length: <no of elements> and __proto__: HTMLCollection 
2. <no of elements> 
3. First Element 
: 나는 jsfiddle에서 제공

1. An object [item:function, namedItem:function], which has all the elements and a length: <number of elements> and __proto___: HTMLCollection (As Expected) 
2. 0 
3. undefined 

같은 일이, 내가 적절한 출력을 얻을

사용되는 자바 스크립트가 동일 할 때 왜 반복 할 수 없습니까? Chrome 확장 프로그램을 사용할 때해야 할 일이 있습니까? '

Heres는 내 manifest.json을 할 경우에 도움이 :

{ 
    "manifest_version": 2, 
    "name": "Something", 
    "description": "Something something...", 
    "version": "1.0", 

    "permissions": [ 
     "tabs", 
     "notifications", 
     "http://*/", 
     "https://*/" 
    ], 

    "content_scripts": [{ 
     "matches": ["https://*","http://*"], 
     "js": ["testscript.js"], 
     "run_at": "document_end" 
    }], 
    "web_accessible_resources": ["samplejs.js"], 

    "browser_action": { 
    "default_popup": "popup.html" 
    } 
} 

내 자바 스크립트 코드는 testscript.js

+0

어디에서 컬렉션을 가져 오려고합니까? –

+0

궁극적으로 모든 페이지의 DOM 내용을 수정하기 위해 content_scripts와 함께 크롬 확장을 작성합니다. –

+0

위의 코드는'testscript.js'의 코드입니다. –

답변

0

해결책을 찾았습니다. 문제는 DOM이 완전히로드되지 않았기 때문에 DOM이로드되기 전에 실행 된 스크립트가 데이터를 올바르게 가져올 수 없다는 것이 내가 추측하는 것입니다.

나는
window.onload=function(){} 

위해 window.onload 문제 출력을 가져 오는 있었다

document.onload=function(){} 

를 사용했는데, document.onload 전혀 유발하지 않습니다.

그래서, 지연 사용하여 시도 :

setTimeout(function(){ 
     <javascript code> 
},3000); 

을 그리고 이것은 잘 작동합니다. 가장 좋은 방법인지 확실하지 않습니다. 대안으로

는 확장에 JQuery와 및 사용에 추가 :

$(document).ready(function(){ 
     <javascript code> 
}); 

을 그리고 이것은 더 나은 작동합니다.

1

음에, 당신의 manifest 파일에 일부 수정을했고, 그것은 나를 위해 일한입니다. 나는 permissionsmatches 부분을 변경 한

{ 
    "manifest_version": 2, 
    "name": "Something", 
    "description": "Something something...", 
    "version": "1.0", 

    "permissions": [ 
    "tabs", 
    "notifications", 
    "http://*/", 
    "http://*/*", 
    "https://*/*" 
    ], 

    "content_scripts": [{ 
    "matches": ["https://*/*", "http://*/*"], 
    "js": ["testscript.js"], 
    "run_at": "document_end" 
    }], 
    "web_accessible_resources": ["samplejs.js"], 

    "browser_action": { 
    "default_popup": "popup.html" 
    } 
} 

: 여기에 업데이트 된 버전입니다.

+0

제안 된대로 변경되었지만 동일한 결과가 발생합니다. :-( –

+0

Dunno가 도움이되지만 Developer Tools를 통해 확인하는 경우 jsfiddle [div.testclass, div.testclass, div.testclass, div와 같이 div에 이름이 표시됩니다.testclass, item : function, namedItem : function]을 사용하지만 주입 된 코드를 통해 [item : function, namedItem : function] 만 표시됩니다. –

+0

확장 프로그램을 https://www.sendspace.com/file/hk0s2m에 업로드했습니다. 그것을 다운로드하고, 압축을 풀고, 'unpacked extension'으로 크롬에로드하십시오. 그런 다음이 페이지 (이 질문의 페이지)로 가서'콘솔 '을여십시오. 나는'testclass' 대신'default' 클래스를 사용했습니다. –

관련 문제