使用Chrome扩展程序更改DOM内容 [英] Change DOM Content With Chrome Extension

查看:145
本文介绍了使用Chrome扩展程序更改DOM内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建Chrome扩展程序。我试图让我的应用程序与扩展中的每个页面以及用户在浏览器中查看的页面进行通信。我需要从扩展中访问dom,然后进行更新。

  manifest.json 
popup.html
popup.js
background.js
content.js

和用户正在查看的当前页面。



我的目标是在页面加载时修改dom并在用户看到它之前向用户显示新版本的页面。 $ popup.js 中的
允许用户在弹出框中输入关键字。这些关键字被保存到 localStorage ,并且当他们查看网页时,通过使关键字的父分区隐藏在任何页面上正在观看。

我需要帮助获取每个页面进行通信,我认为我隐藏在popup.js中的父级div的方式不起作用。



将dom发送到background.js
在页面上查找关键字并更改他们的父母divs隐藏起来。
将dom推回到查看页面。



我认为这行是说如果我匹配任何网址,然后运行我的应用程序,但我不确定。 / p>

 matches:[*:// * / *],

我的manifest.json

  {
name:Wuno Zensoring,
版本:1.0,
权限:[
activeTab,
标签,
存储
],
description:该扩展将搜索文档文件中的关键字并隐藏它们的父div。,
icons:{
19:icon19.png,
38:icon38.png,
48:icon48.png,
128:icon128.png

background:{
persistent:false,
scripts:[jquery-1.11.3.min.js,background.js ]
},
content_scripts:[{
matches:[*:// * / *],
js:[content。 js],
run_at:document_end,
all_frames:true
}],
web_accessible_resources:[
popup.js,content.js
],
browser_action: {
default_icon:icon.png128,
default_popup:popup.html,
default_icon:{
19:icon19.png ,
38:icon38.png,
48:icon48.png,
128:icon128.png
}
$ b $ manifest_version $ 2



popup.html

 <!doctype html> 
< html>
< head>
< title> Wuno Zensorship< / title>
< script src =jquery-1.11.3.min.js>< / script>
< script src =popup.js>< / script>
< link rel =stylesheettype =text / csshref =styles.css>
< / head>
< body>
< img src =icon48.png>

< section>
< form id =formaction =#method =POST>
< input id =descriptionname =descriptiontype =text/>
< input id =addtype =submitvalue =Add/>
< button id =clearChecked>清除选中的项目< / button>
< button id =clear>全部清除< /按钮>
< / form>
< div id =alert>< / div>
< ul id =keyWords>< / ul>
< / body>
< / html>



popup.js

  $(document).ready(function(){
localArray = [];

if(!localStorage.keyWords){
localStorage.setItem( 'keyWords',JSON.stringify(localArray));
}

loadKeyWords();

函数loadKeyWords(){
$('# ();
localArray = JSON.parse(localStorage.getItem('keyWords'));
for(var i = 0; i< localArray.length; i ++) {
'('#keyWords')。prepend('< li>< input class =checkname =checktype =checkbox>'+ localArray [i] +'< / li>');
}
}

$('#add')。click(function(){
var Description = $('#description ').val();
if($(#description).val()===''){
$('#alert')。html(< strong> );
$('#alert')。fadeIn()。delay(1000).fadeOut();
return false;
}
$( '#form')[0] .reset();
var keyWords = $('#keyWords')。html();
localArray.push(描述);
localStorage.setItem('keyWords',JSON.stringify(localArray));
loadKeyWords();
返回false;
});

$('#clear')。click(function(){
window.localStorage.clear();
location.reload();
return false ;
}); (函数(){
currentArray = [];
$('。check')。 b $ b var $ curr = $(this);
if(!$ curr.is(':checked')){
var value = $ curr.parent()。text();
currentArray.push(value);
localStorage.setItem('keyWords',JSON.stringify(currentArray));
loadKeyWords();
} else {
$ curr.parent()。remove();
}
});
});


//用新数据
函数更新相关字段setDOMInfo(info){
$(div p:contains(localStorage.getItem('KeyWords '))母体(' DIV)隐藏())。
}

//一旦DOM准备就绪...
window.addEventListener('DOMContentLoaded',function(){
// ...查询活动标签...
chrome.tabs.query({
active:true,
currentWindow:true
},function(tabs){
//。 ...并发送一个DOM信息请求...
chrome.tabs.sendMessage(
tabs [0] .id,
{from:'popup',subject:'DOMInfo' },
// ...还指定一个回调被称为
//从接收端(内容脚本)
setDOMInfo);
});
});


}); //文档就绪函数结束

background.js

  chrome.runtime.onMessage.addListener(函数(msg,sender){
//首先验证消息的结构
if((msg.from ==='content')&&(msg.subject ==='showPageAction')){
//为请求标签启用页面操作
chrome.pageAction.show(sender .tab.id);
}
});

content.js

  //通知后台页面
//此页面应该有页面操作
chrome.runtime.sendMessage({
from:'content',
主题:'showPageAction'
});

//监听弹出消息
chrome.runtime.onMessage.addListener(函数(msg,sender,response){
//首先验证消息的结构
if((msg.from ==='popup')&&(msg.subject ==='DOMInfo')){
//收集必要的数据
//(对于你的具体需求,document.querySelectorAll(...)`
//应该等价于jquery的`$(...)`)
var domInfo = {
total:document。 querySelectorAll('*')。length,
inputs:document.querySelectorAll('input')。length,
buttons:document.querySelectorAll('button')。length
};

//通过指定的回调* /
响应(domInfo);
}
})直接响应发件人(弹出),
//;


解决方案

您需要使用此查询将数据发送到DOM从当前标签查看。

  chrome.tabs.executeScript(null,{
code:'var config = '+ JSON.stringify(getKeywords)
},function(){
chrome.tabs.executeScript(null,{file:'custom.js'});
});

以及 custom.js 文件中可以编写你想要在DOM元素上应用的函数。就像如果你想在 custom.js 中隐藏某些内容而不是你需要的那样。因此,如果您想使用该示例,则需要根据您的要求进行修改。

  var all = document.getElementsByTagName( DIV); 
var searchValue = config.toString()。split(',');
alert('Example:'+ searchValue [0]); (i = 0; i if(all [i])的
对于(j = 0; j .innerHTML.indexOf(searchValue [j])> -1){
all [i] .innerHTML =
}
}
}


I am building a Chrome extension. I am trying to get my app to communicate with each page in the extension and the page the user is viewing in the browser. I need to access the dom from the extension and then update it.

manifest.json 
popup.html
popup.js
background.js 
content.js

and the current page the user is viewing.

My goal is on page load modify the dom and show the user the new version of the page before they ever see it. in popup.js users are allowed to enter keywords into the popup. The keywords are saved to localStorage and while they view the web the keywords are censored out of their view by making the parent div of the keywords hidden if it is found on any pages they are viewing.

I need help getting each page to communicate and I think the way I am hiding the parent divs in popup.js won't work. I am confused on how to perform the action on the dom from the front.

Send the dom to the background.js Find keywords on the page and change their parent divs to hidden. push the dom back to the viewing page.

I think this line is saying if I match any url then run my app but I am not sure.

  "matches":    ["*://*/*"],

My manifest.json

{
 "name": "Wuno Zensoring",
  "version" : "1.0",
   "permissions": [
   "activeTab",
   "tabs",
   "storage"
   ],
  "description": "This extension will search the document file for keywords and hide their parent div.",
  "icons": {                   
    "19": "icon19.png",
    "38": "icon38.png",
    "48": "icon48.png",
    "128": "icon128.png"  
  },    
    "background": {
    "persistent": false,
    "scripts": ["jquery-1.11.3.min.js","background.js"]
  },
     "content_scripts": [{
        "matches":    ["*://*/*"],
        "js":         ["content.js"],
        "run_at": "document_end",
        "all_frames": true
    }],
     "web_accessible_resources": [
        "popup.js", "content.js"
        ],
  "browser_action": {
    "default_icon": "icon.png128",
    "default_popup": "popup.html",
    "default_icon": {                   
      "19": "icon19.png",
      "38": "icon38.png",
      "48": "icon48.png",
      "128": "icon128.png"        
  }
  },
     "manifest_version": 2
}

popup.html

<!doctype html>
<html>
  <head>
    <title>Wuno Zensorship</title>
    <script src="jquery-1.11.3.min.js"></script>
        <script src="popup.js"></script>
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
    <img src="icon48.png">

 <section>
<form id="form" action="#" method="POST">
<input id="description" name="description" type="text" />
<input id="add" type="submit" value="Add" />
<button id="clearChecked">Clear Checked Items</button>
<button id="clear">Clear All</button>
</form>
<div id="alert"></div>
<ul id="keyWords"></ul>
</body>
</html>

popup.js

   $(document).ready(function () {
localArray = [];

if (!localStorage.keyWords) {
  localStorage.setItem('keyWords', JSON.stringify(localArray));
}

loadKeyWords();

function loadKeyWords() {
    $('#keyWords').html('');
    localArray = JSON.parse(localStorage.getItem('keyWords'));
    for(var i = 0; i < localArray.length; i++) {
      $('#keyWords').prepend('<li><input class="check" name="check" type="checkbox">'+localArray[i]+'</li>'); 
        }
    }

$('#add').click( function() {
   var Description = $('#description').val();
  if($("#description").val() === '') {
    $('#alert').html("<strong>Warning!</strong> You left the to-do empty");
    $('#alert').fadeIn().delay(1000).fadeOut();
    return false;
   }
   $('#form')[0].reset();
   var keyWords = $('#keyWords').html();
   localArray.push(Description);
   localStorage.setItem('keyWords', JSON.stringify(localArray));
   loadKeyWords();
   return false;
});

$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});

$('#clearChecked').click(function() {
  currentArray = [];
  $('.check').each(function() {
    var $curr = $(this);
    if (!$curr.is(':checked')) {
      var value = $curr.parent().text();
      currentArray.push(value);
      localStorage.setItem('keyWords', JSON.stringify(currentArray));
      loadKeyWords();
    } else {
      $curr.parent().remove();
    }
  });
});


// Update the relevant fields with the new data
function setDOMInfo(info) {
  $("div p:contains(localStorage.getItem('keyWords')).parent('div').hide()");
}

// Once the DOM is ready...
window.addEventListener('DOMContentLoaded', function () {
  // ...query for the active tab...
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, function (tabs) {
    // ...and send a request for the DOM info...
    chrome.tabs.sendMessage(
        tabs[0].id,
        {from: 'popup', subject: 'DOMInfo'},
        // ...also specifying a callback to be called 
        //    from the receiving end (content script)
        setDOMInfo);
  });
});


}); // End of document ready function

background.js

chrome.runtime.onMessage.addListener(function (msg, sender) {
  // First, validate the message's structure
  if ((msg.from === 'content') && (msg.subject === 'showPageAction')) {
    // Enable the page-action for the requesting tab
    chrome.pageAction.show(sender.tab.id);
  }
});

content.js

// Inform the background page that 
// this tab should have a page-action
chrome.runtime.sendMessage({
  from:    'content',
  subject: 'showPageAction'
});

// Listen for messages from the popup
chrome.runtime.onMessage.addListener(function (msg, sender, response) {
  // First, validate the message's structure
  if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) {
    // Collect the necessary data 
    // (For your specific requirements `document.querySelectorAll(...)`
    //  should be equivalent to jquery's `$(...)`)
    var domInfo = {
      total:   document.querySelectorAll('*').length,
      inputs:  document.querySelectorAll('input').length,
      buttons: document.querySelectorAll('button').length
    };

    // Directly respond to the sender (popup), 
    // through the specified callback */
    response(domInfo);
  }
});

解决方案

You need to use this query to send data to DOM from the current tab being viewed.

    chrome.tabs.executeScript(null, {
        code: 'var config = ' + JSON.stringify(getKeywords)
    }, function() {
        chrome.tabs.executeScript(null, {file: 'custom.js'});
    });

and in the custom.js file you can write you function that you want to apply on the DOM element. like if you want to hide something than you need that query in custom.js. So if you wanted to use that example you would need to modify it according to your requirements.

var all = document.getElementsByTagName("div");
var searchValue=config.toString().split(',');
alert('Example:' + searchValue[0]);
for(j=0; j < searchValue.length; j++) {
for(i=0; i < all.length; i++) {
    if(all[i].innerHTML.indexOf(searchValue[j]) > -1){
    all[i].innerHTML = ""
    }
}
}

这篇关于使用Chrome扩展程序更改DOM内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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