[javascript] Chrome 확장-DOM 콘텐츠 가져 오기

팝업에서 activeTab DOM 콘텐츠에 액세스하려고합니다. 내 매니페스트는 다음과 같습니다.

{
  "manifest_version": 2,

  "name": "Test",
  "description": "Test script",
  "version": "0.1",

  "permissions": [
    "activeTab",
    "https://api.domain.com/"
  ],

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "Chrome Extension test",
    "default_popup": "index.html"
  }
}

배경 스크립트 (지속성이있는 이벤트 페이지 : false) 또는 content_scripts가가는 길인지 정말 혼란 스럽습니다. 나는 모든 문서 및 기타 SO 게시물을 읽었으며 여전히 나에게 의미가 없습니다.

누군가 내가 왜 다른 것을 사용할 수 있는지 설명 할 수 있습니까?

내가 시도한 background.js는 다음과 같습니다.

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    // LOG THE CONTENTS HERE
    console.log(request.content);
  }
);

그리고 팝업 콘솔에서 이것을 실행하고 있습니다.

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendMessage(tab.id, { }, function(response) {
    console.log(response);
  });
});

나는 얻고있다 :

Port: Could not establish connection. Receiving end does not exist. 

최신 정보:

{
  "manifest_version": 2,

  "name": "test",
  "description": "test",
  "version": "0.1",

  "permissions": [
    "tabs",
    "activeTab",
    "https://api.domain.com/"
  ],

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],

  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "Test",
    "default_popup": "index.html"
  }
}

content.js

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.text && (request.text == "getDOM")) {
      sendResponse({ dom: document.body.innerHTML });
    }
  }
);

popup.html

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendMessage(tab.id, { action: "getDOM" }, function(response) {
    console.log(response);
  });
});

실행할 때 여전히 동일한 오류가 발생합니다.

undefined
Port: Could not establish connection. Receiving end does not exist. lastError:30
undefined



답변

“백그라운드 페이지”, “팝업”, “컨텐츠 스크립트”라는 용어는 여전히 혼란 스럽습니다. Google 크롬 확장 프로그램 문서를 좀 더 자세히 살펴볼 것을 강력히 제안합니다 .

콘텐츠 스크립트 또는 배경 페이지가 적합한 지 질문과 관련하여 :

콘텐츠 스크립트 : 확실히
콘텐츠 스크립트는 웹 페이지의 DOM에 액세스 할 수있는 확장 프로그램의 유일한 구성 요소입니다.

배경 페이지 / 팝업 : 아마도 (아마도 둘 중 최대 1 개)
추가 처리를 위해 콘텐츠 스크립트가 DOM 콘텐츠를 배경 페이지 또는 팝업으로 전달하도록해야 할 수 있습니다.


사용 가능한 문서에 대해 좀 더주의 깊게 연구 할 것을 강력히 권장합니다.
즉, 다음은 StackOverflow 페이지에서 DOM 콘텐츠를 검색하여 백그라운드 페이지로 전송하는 샘플 확장입니다. 그러면 콘솔에서이를 인쇄합니다.

background.js :

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js :

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json :

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  ...

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}


답변

DOM을 얻거나 수정하기 위해 메시지 전달을 사용할 필요가 없습니다. chrome.tabs.executeScript대신 사용 했습니다. 내 예에서는 activeTab 권한 만 사용하고 있으므로 스크립트는 활성 탭에서만 실행됩니다.

manifest.json의 일부

"browser_action": {
    "default_title": "Test",
    "default_popup": "index.html"
},
"permissions": [
    "activeTab",
    "<all_urls>"
]

index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button id="test">TEST!</button>
    <script src="test.js"></script>
  </body>
</html>

test.js

document.getElementById("test").addEventListener('click', () => {
    console.log("Popup DOM fully loaded and parsed");

    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        console.log('Tab script:');
        console.log(document.body);
        return document.body.innerHTML;
    }

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
    chrome.tabs.executeScript({
        code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure
        console.log('Popup script:')
        console.log(results[0]);
    });
});


답변

gkalpak 답변을 시도했지만 작동하지 않는 사람들을 위해,

크롬은 크롬이 실행되는 동안 확장 프로그램이 활성화 된 경우에만 필요한 페이지에 콘텐츠 스크립트를 추가하고 이러한 변경을 수행 한 후 브라우저를 다시 시작하는 것이 좋습니다.


답변