2013-05-07 3 views
2

ahref 태그로 전화 번호를 대체하는 Chrome 확장 프로그램이 있습니다. 이 ahref 태그에서 자바 스크립트 함수를 호출하려고합니다. 단순화하기 위해 href 값으로 "javascript : alert ('hey')"를 사용하고 있습니다. 아래에서 실행할 때 경고 기능에 대해 "regs가 정의되지 않았습니다"가 표시되지만 console.log에는 올바른 값이 표시됩니다. 나는 관련이 있기 때문에 기존의 질문에 덧붙이려고했지만 누군가 그것을 삭제하고 새로운 질문을 게시하도록 요청했다.Chrome 확장 프로그램의 TreeWalker

Chrome extension, making a link from key words in the body

var re = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})/ 
var regs; 

var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, function(node) { 

if((regs = re.exec(node.textContent))) { 

// make sure the text nodes parent doesnt have an attribute we add to know its all ready been highlighted 
if(!node.parentNode.classList.contains('highlighted_text')) { 
var match = document.createElement('A'); 
match.appendChild(document.createTextNode(regs[0])); 
console.log(regs[0]); 
match.href = "javascript:alert(regs[0])"; 
console.log(node.nodeValue); 

// add an attribute so we know this element is one we added 
// Im using a class so you can target it with css easily 
match.classList.add('highlighted_text'); 

var after = node.splitText(regs.index); 
after.nodeValue = after.nodeValue.substring(regs[0].length); 
node.parentNode.insertBefore(match, after); 

} 
} 
return NodeFilter.FILTER_SKIP; 
}, false); 



// Make the walker step through the nodes 
walker.nextNode(); 
+2

'console.log'는 확장 문맥 안에서 실행되기 때문에 올바른 값을 표시합니다.'alert'는 페이지의 컨텍스트에 있기 때문에 그렇지 않습니다. [격리 된 세계] (http://developer.chrome.com/extensions/content_scripts.html#execution-environment)를 참조하십시오. – BeardFist

+0

@BeardFist 사용자가 링크를 클릭 할 때 함수를 호출하는 가장 좋은 방법은 무엇입니까? 이 함수에는 사용자가 클릭 한 전화 번호가 포함되어야합니다. 분명히 클릭 투 다이얼 확장 기능을 구축하십시오. –

+0

['onclick'] (https://developer.mozilla.org/en-US/docs/DOM/element.onclick) 핸들러를 사용하여 코드 내에서 실행되도록하십시오. – BeardFist

답변

0

다음 코드를 사용하여이 작업을 수행했습니다.

match.setAttribute("title", regs[0]); 
match.href = "#"; 
match.addEventListener("click", function(){ make_call('210',this.title); }, false); 

그러면 전화를 담당하는 외부 스크립트에 내선 번호와 전화 번호를 전달하는 XMLHttpRequest를 사용합니다.

우리가 지금 가지고있는 유일한 문제는 Gmail 또는 Google지도에있는 전화 번호와 작동하지 않는다는 것입니다.

0

는 내가 온 클릭을 사용하여 종료하지만 지금은가 호출되는 것과 다른 도메인으로 XMLHttpRequest의 사용에 문제가 실행 해요. Origin ...은 Access-Control-Allow-Origin에서 허용되지 않습니다. 내가하여 addEventListener를 사용하는 대신 위의 방법을 사용하는 방법에 대한 볼거야

match.setAttribute("onclick", "function make_call(extension, phone) { xmlhttp=new XMLHttpRequest();xmlhttp.open('GET','http://[Domain]/click2call.php?extension='+extension+'&phone='+phone,false); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send(null); } ; make_call('210','"+regs[0]+"'); return false; "); 

:

여기에 내가 onclick 이벤트에 사용되는 코드입니다.

+0

얻으려고하는 도메인에 [호스트 권한] (http://developer.chrome.com/extensions/match_patterns.html)을 추가해야합니다. – BeardFist

관련 문제