2016-03-24 55 views
0

我想要做一個鉻擴展名,當用戶點擊擴展按鈕時將用戶重定向到修改鏈接。
我創建了manifest.json,圖標文件,popup.html和popup.js
但我的代碼不工作。如何通過擴展點擊鉻鏈接將用戶重定向到新鏈接?

我已閱讀類似問題的答案,但仍然無法解決問題。 鏈接 - 的什麼,我試圖做>How to modify current url location in chrome via extensions

Pseducode:
當前選項卡(假設WWW [點] xyz.com)
2.Modify URL的1.get URL(abcxyz [點] COM)
3.update鏈接並重定向到新的鏈接(去abcxyz [點] com)

這是我到目前爲止已經寫....

// To get the url 

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { 
    // Do something 
    var targ=tabs[0].url; 

}); 


var toBeOmitted="xyz"; 
    var toBeAddded="abc"; 
    var newTarg=targ.replace(toBeOmitted,toBeAddded); 

//to update to new url 
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tab) { 
     chrome.tabs.update(tab.id, {url:newTarg}); 
}); 

我無法調試它。

回答

0

聲明變量時出現問題。
最終代碼會是這樣的 - >

//Declaring variables 
var targ,newTarg; 

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { 
    // Do something 
    targ=tabs[0].url; 
//defining variables here 
    var toBeOmitted="xyz"; 
    var toBeAddded="abc"; 
//define newTarg without var(to make it global) or just declare outside 
//and define here 
    newTarg=targ.replace(toBeOmitted,toBeAddded); 
    return newTarg; 
}); 





    chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { 
     chrome.tabs.update({url:newTarg}); 
}); 
0

你忘了關閉功能chrome.tabs.query

如果仍然不能正常工作,請嘗試使用null更換tab.id,這樣你也使用chrome.tabs.query

例不需要:

chrome.tabs.update(null, {url:newTarg}); 
+0

它不工作(空的部分)。 其實我錯過了在這裏添加結束部分,但我已經寫在我的代碼中 – Divyanshu

相關問題