Chrome对象或chrome.tabs对象不能从脚本以外的背景脚本访问 [英] chrome object or chrome.tabs object not accessible from script other than a background script

查看:157
本文介绍了Chrome对象或chrome.tabs对象不能从脚本以外的背景脚本访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Chrome扩展API,并遇到了一个我不明白的问题,




我有一个后台脚本background .js和内容脚本content_script.js。


background.js

  chrome.tabs.executeScript({code:console.log('background script')}); 
chrome.tabs .executeScript({file:javascript / content_script.js});
});

内容脚本

  chrome.tabs.executeScript({代码: 的console.log( 'content_script')}); 

后台脚本中的console.log功能完美,但在content_script中的console.log中, 错误 - > 无法读取未定义的属性'executeScript'

这意味着我我无法访问chrome对象或内容脚本中的chrome.tabs对象。为什么会这样?

解决方案

内容脚本在网页上下文中运行,而不是扩展名。



内容脚本无法访问所有Chrome API。根据官方文档


内容脚本是在web
页面的上下文中运行的JavaScript文件。通过使用标准的文档对象模型(DOM),他们可以
读取浏览器访问的网页的详细信息,或者更改


下面是一些内容脚本可以执行的示例:


  • 在网页中查找未链接的网址和将它们转换为超链接
  • 增加字体大小以使文本更清晰可读
  • 查找并处理DOM中的微格式数据


后台脚本是一个单一的长时间运行的脚本来管理某个任务或状态。后台脚本可以访问所有Chrome API。



如果您想在内容脚本和后台脚本之间传递信息,请使用: Chrome消息传递


I am experimenting with the chrome extensions API and I ran into a problem which I don't understand,

I have a background script "background.js" and a content script "content_script.js".

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript({code:"console.log('background script')"});
    chrome.tabs.executeScript({file:"javascript/content_script.js"});
});

content script

chrome.tabs.executeScript({code:"console.log('content_script')"});

The console.log in the background script works perfectly, but in the one in content_script, I get an error --> "Cannot read property 'executeScript' of undefined"

This means that I am not able to access chrome object, or the chrome.tabs object from the content script. Why is this so ?

解决方案

Content scripts run in the context of a web page and not the extension.

Content scripts do not have access to all Chrome APIs. According to official documentation:

Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

Here are some examples of what content scripts can do:

  • Find unlinked URLs in web pages and convert them into hyperlinks
  • Increase the font size to make text more legible
  • Find and process microformat data in the DOM

Background Script is a single long-running script to manage some task or state. While background scripts have access to all Chrome APIs.

If you want to pass information between content scripts and background script use: Chrome Message Passing

这篇关于Chrome对象或chrome.tabs对象不能从脚本以外的背景脚本访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆