内容脚本未执行

时间:2013-10-21 05:38:08

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

我已经创建了chrome扩展,当我点击扩展名时它应该改变它正在工作的页面颜色但是我希望它在页面加载时完成,其中警报显示控件正在通过代码,它不是调用函数同样。请帮忙解决这个问题

---------- -----------的manifest.json

{
  "name": "My Page changer",
  "description": "Make the current page red",
  "version": "2.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_title": "Make this page blue"
  },
  "manifest_version": 2
}
  

------------------ background.js --------------------

debugger;
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status == 'complete') {
    debugger;
        alert('I am here too ');
        /*chrome.tabs.executeScript({
            code: 'document.body.style.backgroundColor="blue"'
            //code : 'doWhatYouWant()'
        });*/
        // Execute some script when the page is fully (DOM) ready
        chrome.tabs.executeScript(null, {code:"doWhatYouWant();"});
    }
});


function doWhatYouWant(){
    alert('I am inside doWhatYouWant');     
    document.body.style.backgroundColor="blue";
}

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  // No tabs or host permissions needed!
  alert('i am here');
  console.log('Turning ' + tab.url + ' red!');
  chrome.tabs.executeScript({
    code: 'document.body.style.backgroundColor="red"'
  });
});

2 个答案:

答案 0 :(得分:2)

您的doWhatYouWant功能存在于您的后台页面中,因此您无法通过内容脚本调用它。

如果要运行的代码长度超过两行,请考虑将其放入扩展中的文件中,并在调用时使用 InjectDetails 参数中的file:字段chrome.tabs.executeScript

此外,如果您希望它在每个页面上运行,您可以将其声明为清单中的内容脚本,而不是拥有chrome.tabs.onUpdated侦听器。

答案 1 :(得分:0)

Google内容脚本教程中有“王子”示例: https://developer.chrome.com/extensions/content_scripts.html#pi 我在学习“google-extenioning”(?)时尝试过并且工作正常。 祝你好运!

eidt - 呃,忘了,文件是here