2015-11-02 83 views
5

我想为Chrome浏览器做一个非常简单的扩展,但我坚持从弹出式html传递一个变量。Chrome浏览器扩展程序:从弹出式窗口传递变量html

这是我的代码至今:


清单:

{ 
    "background": { 
     "scripts": [ "background.js" ] 
    }, 
    "browser_action": { 
     "default_icon": "img/test.png", 
     "default_popup": "popup.html", 
     "default_title": "Auto Clicker" 
    }, 
    "description": "Auto click", 

    "manifest_version": 2, 
    "name": "Auto Clicker", 
    "permissions": [ "activeTab" ], 
    "version": "0.0.1" 
} 

background.js

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) { 
     switch (request.directive) { 

      case "popup-click-1": 
      // execute the content script 
      chrome.tabs.executeScript(null, { // defaults to the current tab 

       file: "myscript.js", // script to inject into page and run in sandbox 
       allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0. 
      }); 
      sendResponse({}); // sending back empty response to sender 
      break; 

     } 
    } 
); 

myscript.js

function foo(){ 
    document.getElementById('submit-button').click(); 
} 

setInterval(function(){ 
    foo()}, 20000) 

foo(); 

popup.js

function clickHandler(e) { 
     chrome.extension.sendMessage({directive: "popup-click-1"}, function(response) { 
      this.close(); // close the popup when the background finishes processing request 
     }); 
    } 


document.addEventListener('DOMContentLoaded', function() { 
     document.getElementById('submit').addEventListener('click', clickHandler); 

    }) 

popup.html

<html> 
<head> 
<title>test</title> 
<script src="popup.js"></script> 
</head> 
<body> 
test 

<form> 
<input id="1" type = "text"> 
</br> 
</form> 
<button id='submit'> etst </button> 
</body> 
</html> 

到目前为止我运行FOO()当您点击提交但是吨,每20秒运行一次。 我想要实现的是在弹出的html中添加一个数字,然后在myscript.js中使用该数字来设置setInterval函数的时间。

因此,这里是一个情况:

我打开网页,我打的扩展按钮。有一个窗体弹出。我把30000,然后击中sumbit。这样,foo()将每30秒运行一次。

+0

1.目前还不清楚是什么问题。 2.在这种情况下,我没有看到需要使用后台脚本(实际上我怀疑你的方案是否有效) – wOxxOm

+0

@wOxxOm 1)我想要获取用户在popup.html表单中输入的变量并替换数字20000与该号码,在myscript.js 2)代码完美的作品,我试了很多次。当您点击popup.html上的提交按钮时,每20秒就会点击一次#提交按钮。 –

回答

3

不需要后台脚本。

注入脚本popup.js和传递值:

function clickHandler(e) { 
    chrome.tabs.executeScript({ 
     code: "var timeout=" + document.getElementById('1').value, 
     allFrames: true 
    }, function(result) { 
     chrome.tabs.executeScript({file: "myscript.js", allFrames: true}, function(result) { 
     }); 
    }); 
} 

myscript.js将采用注入timeout变量:

............. 
setInterval(foo, timeout); 
............. 
+0

Okey,我到目前为止尝试了这么多时间,并且当我使用以下代码时,您的代码工作正常: code:“var timeout = 1;” 然后我去myscript.js并使用警报(超时)并获取值[1]。 问题是,当我使用document.getElementById ....时,它不起作用....任何想法? P.S:我仍然在搜索和测试,但我会更新,如果我有更多的信息 编辑:你是最好的。你的代码工作100%。事实证明,输入(在弹出。HTML)没有ID。 –

+0

使用[调试器(https://developer.chrome.com/extensions/tut_debugging)来检查的变量和表达式的实际值 – wOxxOm

相关问题