简体   繁体   中英

chrome extension not running search into divs jquery code

On chrome extension after doing an ajax call it should search inside paragraphs on divs with id #lead and #detail. If it find a text to add a css class.

My code looks like this :

function retrieveBlicCheckedFacts(tabUrl){
    var data = {currentUrl: tabUrl};
    $.support.cors = true;
    $.ajax({
        type: "POST",
        url: API_URL_FIND,
        crossDomain: true,
        data: JSON.stringify(data),
        contentType: "application/json",
        success: function(respData){
            console.log(respData); //here data are printed correctly
             $("#lead, #detail").find('p').each(function() {
               for (var count = 0; count < respData.length; count++) {
                 var findCheckedFact = respData[count]["text"];
                 var str = $(this).text();
                 console.log(str);
                 if (str.indexOf(findCheckedFact) >= 0) {
                     $(this).html(
                     $(this).html().replace(findCheckedFact, "<span    class='red'> $& </span>")
          );
        }
      }
    });
        },
        error: function(err){
            console.log(JSON.stringify(err));
        }
    });
}

respData is a list like this :

[{"text":"test" , "type":"example" ,"_id": {"$oid": "570e686951d720724aa06fe7"}} ,{"text":"test" , "type":"example", "_id": {"$oid": "570e686951d720724aa06fe8"}} ]

When I debug it goes everything good, except when it comes to paragraphs, it doesn't go inside it, What can be the reason? On manifest js I already add permissions on the selected URL that I want to make those changes. Please help me

Edit: Code above is in checker.js . Here are some code from my manifest.json , http://*www.mydomain.rs/ is my desired domain where I want to make those changes.

  "background": {
    "persistent": false,
    "scripts": [
      "js/jquery-1.12.0.min.js",
      "background.js",
      "checker.js"
    ],
    "css": ["custom-css.css"]
  },
  "permissions": [
    "notifications",
    "contextMenus",
    "storage",
    "tabs",
    "http://*www.mydomain.rs/"
  ], 

Web page code looks something like this:

<!DOCTYPE html>
<html>
<head>
   <title></title>
</head>
<body>
  <div id="trunk">
    <div id="main">
      <div id="lead"> Lorem Ipsum is simply dummy text </div>
      <div id="detail" class="detail intext" itemprop="articleBody">
        <p> What is Lorem Ipsum</p>
        <p> Why do we use it?</p>
        <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text.  </p>
      </div>
    </div>
  </div>
</body>
</html>

Your ajax call is in the background page, it can't directly access the DOM of current page, because they live in different context and would need Message Passing to communicate with each other.

Available methods would be:

  1. Use Content Scripts . You could inject a content script in the current page, when ajax call is returned from background page, you could pass the returned info to content scripts, then do DOM operation in content scripts. Considering your logic, you may also want to send response from content script back to background page.

  2. Use Programming Injection . You could wrap the DOM operation code in a script or some code blocks, then inject it from background page.

     chrome.tabs.executeScript(tabId, {"code": "//Your DOM operation code here"}, function(result) { // Your logic to handle returned value }); chrome.tabs.executeScript(tabId, {file: "xxx.js"}, function(result) { // Your logic to handle returned value }); 

    Code snippets would look like:

     function retrieveBlicCheckedFacts(tabUrl){ var data = {currentUrl: tabUrl}; $.support.cors = true; $.ajax({ type: "POST", url: API_URL_FIND, crossDomain: true, data: JSON.stringify(data), contentType: "application/json", success: function(respData){ console.log(respData); //here data are printed correctly chrome.tabs.executeScript({file: "js/jquery-1.12.0.min.js"}, function() { chrome.tabs.executeScript({"code": '(function(respData){' +'$("#lead, #detail").find("p").each(function() {' +'for (var count = 0; count < respData.length; count++) {' +'var findCheckedFact = respData[count]["text"];' +'var str = $(this).text();' +'console.log(str);' +'if (str.indexOf(findCheckedFact) >= 0) {' +'$(this).html($(this).html().replace(findCheckedFact, "<span class=\\'red\\'> $& </span>"));' +'}' +'}' +'});' +'}(' + JSON.stringify(respData) + '));' }); }); }, error: function(err){ console.log(JSON.stringify(err)); } }); } 

    Don't forget to add js/jquery-1.12.0.min.js to web_accessible_resources section

    manifest.json

     "background": { "persistent": false, "scripts": [ "js/jquery-1.12.0.min.js", "background.js", "checker.js" ], "css": ["custom-css.css"] }, "permissions": [ "notifications", "contextMenus", "storage", "tabs", "http://*www.mydomain.rs/" ], "web_accessible_resources": ["js/jquery-1.12.0.min.js"] 
  3. Move all this logic to content script. If you want to use this way, you may be restricted by SOP , your content scripts would not get the right returned info if you don't enable CORS at your server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM