2

I am trying to learn chrome extensions and I am trying to build a simple one which tries to find if there are forms or not in webpage.

My code is as simple as possible and the following snippet is content script - javascript.js and popup page - index.html.

function sendMessage() {
  chrome.extension.sendMessage({
action: "findurls"
  });
}

document.addEventListener('DOMContentLoaded', function () {
  var show = document.getElementById('show');
  show.addEventListener('click', findValidForms);
  });

const findValidForms = () => {
  let list = [];
  let message = "Available forms are: \n ";
  let forms = document.querySelectorAll('form');
  if (forms.length > 0) {
    for (var i = 0; i < forms.length; i++) {
      list.push(forms[i].action);
      message += `<a href="${list[i]}">${list[i]}</a><br />`;
    }
  }
  else {
    message = "no forms";
  }
  alert(message);
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>testing</title>
 
    <link rel="stylesheet" type="text/css" href="style.css">


</head>

<body>
    <div id="cgi">
        <div class="heading">
            <h3 center> Test title </h3>
        </div>
  
    <div id='ah!'> </div>
    <button id='show'>find forms</button>
    
    <script src="jquery-3.5.0.min.js"></script>
    <script type="text/javascript" src="javascript.js"></script>

</body>

</html>
manifest:
"manifest_version": 2,
    "name": "form",
    "version": "1.0",
    "description": "find form url ",
    "icons": {
        "16": "chrome_16.png",
        "32": "chrome_32.png"

    },

       "background": {
     "scripts": ["background.js"],
     "persistent": false
  },
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "javascript.js",
                "jquery-3.5.0.min.js"
            ],
            "css": [
                "style.css"
            ]
        }
    ],
    "browser_action": {
        "default_icon": "chrome_16.png",
        "default_popup":"index.html",
        "default_title": "test"
    },
    "permissions": [
        "activeTab"
    ]
}

 background.js:
  chrome.extension.onMessage.addListener(
function(request, sender, sendResponse)
{ 
    if (request.action == "findurls")
        chrome.tabs.executeScript({ file: 'test.js' });
}

);

Thanks

  • 1
    I've edited your question to include the [google-chrome-extension] tag, which will help narrow the audience to those people who know extensions. – Heretic Monkey Jun 16 '20 at 15:49
  • I am sorry if I missed it but... what is your question exactly ? – FloT Jun 16 '20 at 16:13
  • how to make it work as chrome extension..i have installed it and when i run it it doesn't work..or to explain it better it shows extension id instead of form urls. – Sofia Giannou Jun 16 '20 at 16:16
  • 1
    @sofia, your event listen given in the content script but the button was placed in popup page. Button click even listener should be moved to popup page script and whenever the button clicked, it will have to send a message to current tab's content script. – Perfect Jun 16 '20 at 16:19

1 Answers1

2

Clicked the button placed in index.html, the extension should send a message to content script - javascript.js in your solution. So the content script needs a event listener that monitors the message triggered from background script. Once it's arrived, the corresponding method should be executed.

Here is the quick link to resolve but let me briefly describe here.

  1. Create a js file (ie index.js) and inject into your index.html. (honestly, popup.html and popup.js will be better than the current name - index). Give this code into the index.js
  2. In your content script - index.js, add the code to listen message sent from the popup page's script (index.js) with handler the current function you created. (Original function name was Forms)

popup.js

const sendMessage = () => {
    chrome.tabs.query(
        {
            active: true,
            currentWindow: true
        }, (tabs) => {
            chrome.tabs.sendMessage(
                tabs[0].id,
                {
                    action: "get-urls"
                }, (response) => {
                    console.log(response)
                }
            );
        }
    );
}

document.addEventListener('DOMContentLoaded', function () {
    var geturls = document.getElementById('btn-get-urls');
    geturls.addEventListener('click', sendMessage);
});

content_script.js

const FindAllForms = () => {
    let list = [],
        message = "Available forms are: \n ",
        availableForms = document.querySelectorAll('form');
    if (availableForms.length > 0) {
      for (var i = 0; i < availableForms.length; i++) {
        list.push(availableForms[i].action);
        message += "<a href=" + list[i] + ">" + list[i] + "</a>" + "\n";
      }
    }
    else {
      message = "no forms";
    }
    alert(message);
}
  
chrome.extension.onMessage.addListener(
   (request, sender, sendResponse) => { 
        if (request.action == "get-urls") {
            FindAllForms()
            sendResponse({'success': true})
        }
    }
);

In the popup script, you should send a message to current/active tab's content script as this answer.

I hope this will help you.

Thank you

Perfect
  • 1,616
  • 1
  • 19
  • 27
  • Thanks @Perfect! I will try your suggestion.A general query though:Why background.js is necessary? – Sofia Giannou Jun 16 '20 at 17:01
  • I tried your suggestion but I got confused in the process.So, I have my html file (index.html) with the button. My javascript file (javascript. js) in my case (--I will change the name later) and in that I have already my function and the event listener for the button. when I click it now it works but it shows my extensions Id. To fix it I must create a background. js file to write a message. But what kind of message is that?? Thats where I am getting confused. – Sofia Giannou Jun 16 '20 at 21:35
  • can you tell once more what i have to do??i haven't made any progress form yesterday because i don't know what kind of message i must write and where.All this situation is confusing! Thank you! – Sofia Giannou Jun 17 '20 at 12:42
  • My latest actions:Created background.js and i used messages but nothing works.I do not know if the message is right.Please,if anyone knows tell me how to fix it.Thanks – Sofia Giannou Jun 17 '20 at 14:17
  • @SofiaGiannou, sorry for my late response. You should send message from background script to active tab. – Perfect Jun 17 '20 at 14:56
  • so everything i have done is wrong?I just can't find a simple example for this and sorry if i am disturbing you a lot – Sofia Giannou Jun 17 '20 at 14:58
  • No, that's okay. If you are available, I will give you some help on it via some messenger like skype or anything else. I think there was a tool to chat each other here on stackoverflow but couldn't find. – Perfect Jun 17 '20 at 15:06
  • I added a link to an answer. Here again. https://stackoverflow.com/questions/14245334/sendmessage-from-extension-background-or-popup-to-content-script-doesnt-work#answer-14245504 – Perfect Jun 17 '20 at 15:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/216146/discussion-between-sofia-giannou-and-perfect). – Sofia Giannou Jun 17 '20 at 15:16
  • it's working!!Thanks!I have 2 queries though:When i run my code in console it actually shows the forms as clickable urls.In alert the form urls are as text..is there a way to have clickable urls in alert?And the second query is:if i add a second button i must do the same thing for it again?Send message to backgoriund etc to make it work? – Sofia Giannou Jun 18 '20 at 12:30