2013-05-07 24 views
2

我有一個Chrome擴展程序,它使用ahref標記替換電話號碼。在這個ahref標記中我想調用一個javascript函數。爲了簡化,我使用「javascript:alert('hey')」作爲href值。當我執行下面的命令時,我得到了「regs is not defined」,但是對於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'不是因爲它在頁面的上下文中。查看[isolated world](http://developer.chrome.com/extensions/content_scripts.html#execution-environment) – BeardFist 2013-05-07 02:02:55

+0

@BeardFist當用戶點擊鏈接時調用函數的最佳方式是什麼?該功能必須包含用戶點擊的電話號碼。顯然建立一個點擊撥號擴展。 – 2013-05-07 05:09:15

+0

只需使用['onclick'](https://developer.mozilla.org/en-US/docs/DOM/element.onclick)處理程序,以便它在您的代碼中執行。 – BeardFist 2013-05-07 05:14:24

回答

0

我們使用下面的代碼得到了這個工作。

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

然後,我們使用XMLHttpRequest,它將擴展名和電話號碼傳遞給負責進行調用的外部腳本。

我們現在唯一的問題是,它不適用於在Gmail或谷歌地圖中找到的電話號碼。

0

我最終使用的onclick但我現在使用的XMLHttpRequest與一個比它被稱爲不同的域遇到了問題。來源...不受Access-Control-Allow-Origin允許。

下面是我用onclick事件的代碼:

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; "); 

我會看到有關使用addEventListener,而不是採用上述方法。

+0

您需要爲您嘗試獲取的域添加[主機權限](http://developer.chrome.com/extensions/match_patterns.html)。 – BeardFist 2013-05-07 16:12:15