使用Chrome扩展程序更改DOM内容

wun*_*uno 23 javascript jquery google-chrome google-chrome-extension

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

manifest.json 
popup.html
popup.js
background.js 
content.js
Run Code Online (Sandbox Code Playgroud)

以及用户正在查看的当前页面.

我的目标是在页面加载时修改dom并在用户看到之前向用户显示新版本的页面.在popup.js用户中允许在弹出窗口中输入关键字.关键字被保存到localStorage他们查看网页时,通过使关键字的父div隐藏(如果在他们正在查看的任何页面上找到关键字),将关键字从其视图中删除.

我需要帮助让每个页面进行通信,我认为我在popup.js中隐藏父div的方式不起作用.我对如何从前面对dom执行操作感到困惑.

将dom发送到background.js在页面上查找关键字并将其父div更改为hidden.将dom推回查看页面.

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

  "matches":    ["*://*/*"],
Run Code Online (Sandbox Code Playgroud)

我的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
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

小智 15

您需要使用此查询从正在查看的当前选项卡将数据发送到DOM.

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

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

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 = ""
    }
}
}
Run Code Online (Sandbox Code Playgroud)


Hai*_* Ai 7

您应该从 background.js 或 popup.js 发送命令,接收该命令并更改 content.js 中的 dom。以下代码演示了一个简单的场景:单击 browserAction 并将一个 div 附加到当前页面。您可以使用相同的逻辑来显示/隐藏任何元素。

清单文件

{
  "name": "Test",
  "version": "1.0",
  "permissions": [
    "tabs"
  ],
  "description": "Test",
  "background": {
    "persistent": false,
    "scripts": [
      "background.js"
    ]
  },
  "content_scripts": [
    {
      "matches": [
        "*://*/*"
      ],
      "js": [
        "content.js"
      ],
      "run_at": "document_end",
      "all_frames": true
    }
  ],
  "browser_action": {
    "title": "Test"
  },
  "manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)

背景.js

chrome.browserAction.onClicked.addListener(function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {command: "append"}, function(response) {
            console.log(response.result);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

内容.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)    {
    console.log(request.command);

    var div = document.createElement('div');
    var label = document.createElement('span');
    label.textContent = "Hello, world";
    div.appendChild(label);
    document.body.appendChild(div);

    sendResponse({result: "success"});
});
Run Code Online (Sandbox Code Playgroud)


gae*_*noM 5

我将尝试尽可能简单地回答这个问题,因为对代码进行更少的更改将帮助您更快地学习。

通常,当最终用户按下弹出窗口上的“开始”按钮时,我会编写以下代码行(请参阅您的popup.js):

chrome.runtime.sendMessage({key: 'popupInit'}, function (response) {
 ;
});
window.close();  // this line closes the popup
Run Code Online (Sandbox Code Playgroud)

非常重要的是要了解响应不是通信系统,而只是来自相应侦听器的即时答案。我的听众是background.js. 在此文件中,您可以利用localStorage以下内容:

chrome.runtime.sendMessage({key: 'popupInit'}, function (response) {
 ;
});
window.close();  // this line closes the popup
Run Code Online (Sandbox Code Playgroud)

chrome.tabs.onUpdated.addListener很重要,因为每次更新活动当前页面时,您都可以将消息发送到内容脚本以获取值localstorage,当弹出窗口关闭时也会发生同样的情况,如果其中有单词,localstorage您可以使用 来chrome.runtime.onMessage.addListener监听信号:弹出窗口关闭,因此开始内容脚本中的工作,向其发送包含单词数组的消息。

现在让我们看一下您的content.js文件。

chrome.tabs.onUpdated.addListener(function(tabid, changeInfo, tab) {
  if (typeof changeInfo.status == 'string' && changeInfo.status == 'complete') {
    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
      var keyString = JSON.parse(localStorage.getItem('keyWords'));
      chrome.tabs.sendMessage(tabs[0].id, {key: 'init', wordToHide: keyString}, function (response) {
        ;
      });
    });
  }
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  var rq = request.key;
  if (rq != undefined && typeof rq == 'string') {
    switch (rq) {
      case 'popupInit':
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          var keyString = JSON.parse(localStorage.getItem('keyWords'));
          chrome.tabs.sendMessage(tabs[0].id, msgToSend, function(response) {
            ;
          });
        });
        break;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

我尝试隐藏整个页面:请注意这一点,因为它可能很复杂(请记住,最终用户在页面加载时必须始终看到某些内容......)。

之后,content.js等待来自后台的消息,当发生这种情况时,内容脚本开始工作!就这样。

抱歉我的写作中出现了混乱。如果您需要其他帮助,请告诉我。我测试了您的分机并在您可以看到的地方进行了更正。

对于 Chrome 扩展中的组件之间的通信,您需要记住:

  • 背景是大听众
  • 弹出窗口与后台通信
  • 背景与内容沟通

要发送/接收消息,您可以查看Chrome 消息传递

  1. 该函数chrome.runtime.sendMessage({greeting: "hello"}, function(response) { console.log(response.farewell); });用于发送
  2. chrome.runtime.onMessage.addListener是服务器(接收者)

sendResponse响应仅用于动态检查有关通信的信息:例如:您好 --> 好吧,我明白了,现在我自己继续。

我还完成了你的单词替换部分!