2015-11-02 82 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

相關問題