如何制作Chrome扩展程序以打开网络表单并自动填充特定输入字段?

时间:2017-09-04 13:58:38

标签: javascript google-chrome google-chrome-extension

我是使用Chrome扩展程序的新手,我在设置Chrome扩展程序时遇到了一些问题。我希望扩展从网页中读取特定值,然后从我在新选项卡中构建的烧瓶应用程序中打开一个特定页面(带有许多输入字段的表单),然后使用已经刮到的值从我的烧瓶应用程序填充页面中的特定字段。

我设法获得扩展程序以生成新标签页并从我的烧瓶应用程序加载页面但我无法填充字段。在填充字段之前,似乎会加载页面。我已经贴了一些代码来告诉你我有多远。另一个问题是我使用executeScripts中的code参数来执行填充操作,但我似乎无法将参数传递给代码字符串(我怀疑这不是这样做的方法,但我正在努力从这里开始,我发现答案非常有用https://stackoverflow.com/a/41094570/1977981 任何帮助将不胜感激。

的manifest.json

{
  "manifest_version": 2,
  "name": "My Cool Extension",
  "version": "0.1",
  "permissions": [
  "http://localhost:****/lesson/1/note/new/"
    ],
  "content_scripts": [
  {
  "matches": [
    "<all_urls>"
    ],
  "js": ["jquery-3.2.1.min.js", "content.js"]
  }
 ],
  "browser_action": {
  "default_icon": "icon.png"
 },
  "background": {
  "scripts": ["jquery-3.2.1.min.js", "background.js"]
 }
}

content.js

// Triggered by sendMessage function in background.js
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        // listening for request message
        if( request.message === "clicked_browser_action" ) {
            //  Retrieve Lesson title from current tab
            var lesson = $('._tabbed-sidebar--title--1Dx5w').find('span').text()

            // output this value to the console
            console.log(lesson);

            // Send a single message to the event listener in your extension i.e. background.js

          chrome.runtime.sendMessage({"message": "open_new_tab", "lesson": lesson})
    }
  }
);

background.js

// Called when the user clicks on the browser action icon.
chrome.browserAction.onClicked.addListener(function(tab) {

    // Send a message to the active tab
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

    // take the current tab shown in the window
    var activeTab = tabs[0];

    // Send a message to contents.js - this message is being listened for by contents.js and the runtime.onMessage event is fired in content.js script
    chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});

      });
});

// listening for "open_new_tab" message from content.js
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if( request.message === "open_new_tab" ) {

            // create new tab but do not activate the tab yet
            chrome.tabs.create({"url": "http://localhost:5000/lesson/1/note/new/", active: false }, function(tab){


                // load jquery functionality execute script
                chrome.tabs.executeScript(tab.id, {file: "jquery-3.2.1.min.js"}, function(results){

                    chrome.tabs.executeScript(tab.id,{code:`
                       (function(arguments){
                           var count = 100; //Only try 100 times
                           function autofill(){
                               var lesson = $('.lesson_subsection');
                               console.log(lesson);
                               if(lesson){
                                   lesson.value = arguments[0].lesson;
                               } else {
                                   if(count-- > 0 ){
                                   //The elements we need don't exist yet, wait a bit to try again.
                                       setTimeout(autofill,250);
                                    }
                               }
                           }
                           autofill();
                       }, request)();
                   `}, function(results){

                    chrome.tabs.update(tab.id,{active:true});
                          }); //END OF second executeScript function
}); // END OF first executeScript function

    } // END OF chrome.tabs.create anonymous function
    ); // END OF chrome.tabs.create
} // END OF if( request.message === "open_new_tab" ) {
}); // END OF addListener anonymous function

1 个答案:

答案 0 :(得分:0)

谢谢@wOxxOm您的评论非常有帮助。我能够使用JSON.stringify将参数加载到注入的代码字符串中。我还必须使用document.getElementsByClassName()从我的表单加载input元素,而不是使用对象的jquery版本。这也意味着我不必加载jquery库,见下面的行

  

var less = document.getElementsByClassName('lesson_subsection')[0];

现在我的background.js脚本中的chrome.runtime.onMessage.addListener函数如下:

// See content.js function
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if( request.message === "open_new_tab" ) {
            chrome.tabs.create({"url": "http://localhost:5000/lesson/1/note/new/", active: false }, function(tab){
            console.log('Attempting to inject script into tab:',tab);
            chrome.tabs.executeScript(tab.id,{code:`
                (function(argument){
                     var count = 100; //Only try 100 times
                     function autofill(){
                     var less = document.getElementsByClassName('lesson_subsection')[0];
                     if(less){
                         less.value = argument;
                     } else {
                           if(count-- > 0 ){
                               //The elements we need don't exist yet, wait a bit to try again.
                               setTimeout(autofill,250);
                    }
                }
            }
            autofill();
        })(` + JSON.stringify(request.lesson) + `);
    `}, function(results){
            // chrome.tabs.sendMessage(tab.id, {"message": "need to update tab", "tab": tab.id});
            chrome.tabs.update(tab.id, { active: true });

    }); //END OF executeScript function

    } // END OF chrome.tabs.create anonymous function
    ); // END OF chrome.tabs.create
  } // END OF if( request.message === "open_new_tab" ) {
}); // END OF addListener anonymous function