Google Chrome Extension - Accessing The DOM

2019-01-09 00:07发布

I have been searching around the web to find out how to access the current tabs DOM to extract information out of a page from the background.html. So far I have had no luck, or at least nothing I could get to work properly.

To state the problem simply. I would like to get src of a iFrame on the page. Any Suggestions?

1条回答
叛逆
2楼-- · 2019-01-09 00:20

One way, you an treat this as a single one time request to the content-script which will fetch the dom you want to access. http://code.google.com/chrome/extensions/messaging.html#simple

Basically, your content script sets up the listener:

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
    else
      sendResponse({}); // snub them.
  });

And your background page sends a single lived request:

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

When you send your response, you send it as JSON data, you can fetch whatever you want (such as html, dom, text, etc).

That is currently the only way to let the background page know anything about the contents of a page. Remember you would need content scripts and tab permissions.

查看更多
登录 后发表回答