program story

크롬 확장 프로그램의 현재 탭 URL을 어떻게 얻을 수 있습니까?

inputbox 2020. 12. 14. 08:09
반응형

크롬 확장 프로그램의 현재 탭 URL을 어떻게 얻을 수 있습니까?


비슷한 질문이 많이 있다는 것을 알고 있지만 제대로 작동하지 않는 것 같습니다.

Chrome 확장 프로그램에서 현재 탭의 URL을 가져 오려고합니다. 그러나 alert (tab.url)은 "Undefined"를 반환합니다. manifest.json의 내 권한에 "탭"을 추가했습니다. 어떤 아이디어?

<html>
<head>
<script>

    chrome.tabs.getSelected(null, function(tab) {
        tab = tab.id;
        tabUrl = tab.url;

        alert(tab.url);
    });

</script>
</head>

문제는 다음 줄에 있습니다.

tab = tab.id;

다음과 같아야합니다.

var tabId = tab.id;

Google 직원을위한 참고 자료 :

OP에서 사용하는 방법은 더 이상 사용되지 않습니다. 사용자가보고있는 탭을 가져 오려면 사용자가보고있는 창에서만 다음을 사용하십시오.

  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

     // since only one tab should be active and in the current window at once
     // the return variable should only have one entry
     var activeTab = tabs[0];
     var activeTabId = activeTab.id; // or do whatever you need

  });

이것은 나를 위해 일한 것입니다.

chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function(tabs) {
    // and use that tab to fill in out title and url
    var tab = tabs[0];
    console.log(tab.url);
    alert(tab.url);
});

ES6의 약간의 도움으로 더 좋은 코드를 쉽게 작성할 수 있습니다. :)

chrome.tabs.query({
  active: true,
  currentWindow: true
}, ([currentTab]) => {
  console.log(currentTab.id);
});

manifest.json에서 :

"permissions": [
    "tabs"
] 

JavaScript에서 :

chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function(tabs) {
    // and use that tab to fill in out title and url
    var tab = tabs[0];
    console.log(tab.url);
    alert(tab.url);
});

참고 URL : https://stackoverflow.com/questions/6132018/how-can-i-get-the-current-tab-url-for-chrome-extension

반응형