在background.html中,如何访问当前网页以获取dom [英] In background.html,how can I access current web page to get dom

查看:1165
本文介绍了在background.html中,如何访问当前网页以获取dom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在background.html中,我想获取当前的网页dom。
例如getElementById()

解决方案

为此,您需要使用消息传递。需要消息传递以允许您与DOM进行通信,并且唯一的沟通方式是方法1

让每个访问过的页面监听扩展请求

background.html



 <$ c 
< script>
chrome.tabs.getSelected(null,function(tab){
chrome.tabs.sendRequest(tab.id,{method: getHTML},函数(响应){
console.log(response.data);
});
});
< / script>
< ; / html>



content_script.js



  chrome.extension.onRequest.addListener(function(request,sender,sendResponse){
if(request.method ==getHTML)
sendResponse({data:document.getElementById('header')。innerHTML});
else
sendResponse({}); //缓解他们。
});



方法2



只执行一个内容脚本,只要你需要:

background.html



 < HTML> 
< script>
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.executeScript(tab.id,{file:'execute.js'});
});

chrome.extension.onRequest.addListener(function(request,sender,sendResponse){
console.log('Data Recieved:'+ request.data);
}) ;
< / script>
< / html>



execute.js



  chrome.extension.sendRequest({data:document.getElementById('header')。innerHTML}); 


In background.html,I want to get current web page dom. such as "getElementById()

解决方案

To do this, you would need to use Message Passing. Message passing is needed to allow you to communicate to the DOM, and the only way to communicate to the DOM is through Content-Scripts. I will show you two ways which you can do this:

Method 1

Having every visited page listen for an extension request

background.html

<html>
<script>
chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendRequest(tab.id, {method: "getHTML"}, function(response) {
    console.log(response.data);
  });
});
</script>
</html>

content_script.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "getHTML")
      sendResponse({data: document.getElementById('header').innerHTML});
    else
      sendResponse({}); // snub them.
});

Method 2

Only execute a content script whenever you need to:

background.html

<html>
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(tab.id, {file: 'execute.js'});
});

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  console.log('Data Recieved: ' + request.data);
});
</script>
</html>

execute.js

chrome.extension.sendRequest({data: document.getElementById('header').innerHTML});

这篇关于在background.html中,如何访问当前网页以获取dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆