[英]Chrome extension to detect locale of current tab
I want to show the locale(lang attribute of html source code) of the tab selected and display it in my popup.html of Chrome-Extension. 我想显示所选选项卡的语言环境(html源代码的lang属性),并将其显示在我的Chrome-Extension的popup.html中。 For doing this.
为此。 My popup.html is:
我的popup.html是:
<div id="pageLocale">Page Locale is: <b> <script src="write.js"></script></b></div>
My write.js is: 我的write.js是:
chrome.tabs.executeScript(null,{code:"document.write(document.documentElement.lang)"});
If I use this, I get the content of my selected tab all blank and only the locale string. 如果使用此选项,则我选择的选项卡的内容将全部为空白,而只有区域设置字符串。 I understand what is the issue here.
我了解这里的问题。 I want to know, how I can extract lang attribute using "document.documentElement.lang" for the current tab and return it to my popup.html.
我想知道如何使用当前标签的“ document.documentElement.lang”提取lang属性并将其返回到我的popup.html。 The current tab selected should not go blank when I click chrome-extension icon.
当我单击chrome-extension图标时,当前选定的标签不会空白。 Please help guys.
请帮助大家。
By calling document.write
in chrome.tabs.executeScript
, you're overwriting the content of the document (as you've observed). 通过在
chrome.tabs.executeScript
调用document.write
,您将覆盖文档的内容(如您所见)。 Often, you should not use document.write
. 通常,您不应该使用
document.write
。
And don't use document.documentElement.lang
, because it can be empty if not set by the page. 并且不要使用
document.documentElement.lang
,因为如果页面未设置它可以为空。 Instead, use chrome.tabs.detectLanguage
. 而是使用
chrome.tabs.detectLanguage
。 Here's an example: 这是一个例子:
// write.js
(function() {
var thisScriptElement = document.currentScript;
chrome.tabs.detectLanguage(null, function(language) {
var node = document.createTextNode(language);
// Replace <script> with the text
thisScriptElement.parentNode.replaceChild(node, thisScriptElement);
});
})();
If you really want to get the value of the lang
attribute (even if it is an empty string), then you need to use chrome.tabs.executeScript
as follows: 如果您确实要获取
lang
属性的值(即使它是一个空字符串),则需要使用chrome.tabs.executeScript
,如下所示:
// write.js
(function() {
var thisScriptElement = document.currentScript;
chrome.tabs.executeScript(null, {
code: 'document.documentElement.lang;'
}, function(result) {
var language = result[0]; // Last expression's result in the top frame.
var node = document.createTextNode(language);
// Replace <script> with the text
thisScriptElement.parentNode.replaceChild(node, thisScriptElement);
});
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.