2016-03-24 38 views
0

如果用戶訪問存儲在我的數據庫中的URL,我想創建一個DIV包含消息。其實,它工作在一個警告消息,但我想DIV,所以我應該通過contentscript.js訪問頁面的DOM,它的工作,但我怎麼能防止功能工作在contentscript.js因爲我希望函數工作後I檢查了background.js中的URL!Chrome擴展程序:從background.js中的contentscript.js調用函數

我閱讀關於選項卡,但只有當用戶點擊瀏覽器動作的圖標時運行,並在我的情況下,用戶沒有點擊任何他只是在www瀏覽的圖標。

contentscript.js

chrome.runtime.sendMessage(window.location.href); 
var pathname = window.location.pathname; // Returns path only 
var url  = window.location.href; 
//document.getElementsByTagName('title')[0].innerText 

function MessageBox(){ 
    document.documentElement.style.height = '100%'; 
    document.body.style.height = '100%'; 
    document.documentElement.style.width = '100%'; 
    document.body.style.width = '100%'; 

    var div = document.createElement('div'); 
    var btnForm = document.createElement('form'); 
    var btn = document.createElement('input'); 

    //append all elements 
    document.body.appendChild(div); 
    div.appendChild(btnForm); 
    btnForm.appendChild(btn); 
    //set attributes for div 
    div.id = 'myDivId'; 
    div.style.position = 'fixed'; 
    div.style.top = '80%'; 
    div.style.left = '77%'; 
    div.style.width = '22%'; 
    div.style.height = '17%'; 
    div.style.backgroundColor = 'white'; 
    div.style.border='1px solid red'; 

    //set attributes for btnForm 
    btnForm.action = ''; 

    //set attributes for btn 
    //"btn.removeAttribute('style'); 
    btn.type = 'button'; 
    btn.value = 'X'; 
    btn.style.position = 'reltive'; 
    btn.style.top = '10%'; 
    btn.style.left = '80%'; 
    btn.style.width = '5%'; 
    btn.style.height = '3%'; 
} 

background.js

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) { 

    $.ajax({ 
     type: 'GET', 
     url: 'http://mywebsite.com/api/route', 
     dataType: 'json', 
    }).success(function(results) { 
     for (var i = 0; i < results.length; i++) { 
      if (results[i].url === response) { 
       alert("This page in my database"); // this work but I don't want an alert message 
      } //if 
     } //for 
    }); 
}); 

回答

0

chrome.runtime.sendMessage是異步方法。當你完成你的工作

在你的後臺腳本,你可以通過它的回調方法,並在後臺腳本調用sendResponse

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) { 

    $.ajax({ 
     type: 'GET', 
     url: 'http://mywebsite.com/api/route', 
     dataType: 'json', 
    }).success(function(results) { 
     for (var i = 0; i < results.length; i++) { 
      if (results[i].url === response) { 
       sendResponse(true); 
       return; 
      } 
     } 

     sendResponse(false); 
    }); 

    return true; // tell chrome about runnning async job 
}); 

而在你的內容腳本做到這一點

chrome.runtime.sendMessage(window.location.href, function(result) { 
    if (result) { 
     // Found 
     MessageBox(); 
    } 
}); 

瞭解更多消息在這裏傳遞https://developer.chrome.com/extensions/messaging

+0

非常感謝你的工作 – Seham

相關問題