【问题标题】:Javascript - Getting a page title and meta description and using them as variables for a chrome extensionJavascript - 获取页面标题和元描述并将它们用作 chrome 扩展的变量
【发布时间】:2013-10-26 01:13:58
【问题描述】:

我有一个脚本,它从选项卡中获取标题并将其分配给一个变量。但是,我还需要获取 meta desctitle 属性以在 input 字段中使用。

我不确定我是否可以通过以下方式实现:

chrome.tabs.getSelected(null, function(tab) {  
    var currentTitle = tab.title;  
});

然后我需要获取 Meta 描述,我不相信我可以从标签数据中获取。

这是我从中获取描述的 HTML:

<meta name="description" content="contentstuffya" />

这是我用来在扩展之外获取它的 Javascript:

document.getElementsByName('description')[0].getAttribute('content');

鉴于我拥有的数据,我将如何最好地做到这一点?

【问题讨论】:

  • 那行包含description 的html 是什么样子的?

标签: javascript google-chrome-extension


【解决方案1】:

一个更好的方法是使用它。

  function getMeta(metaName) {
   const metas = document.getElementsByTagName('meta');

   for (let i = 0; i < metas.length; i++) {
    if (metas[i].getAttribute('name') === metaName) {
      return metas[i].getAttribute('content');
    }
   }

   return '';
  }

  console.log(getMeta('description'));

要获得标题,您可以使用

console.log(document.title)

How do I get the information from a meta tag with JavaScript?

【讨论】:

    【解决方案2】:

    &lt;meta&gt; 标签的值只能通过内容脚本读取。这是一个例子:

    var code = 'var meta = document.querySelector("meta[name=\'description\']");' + 
               'if (meta) meta = meta.getAttribute("content");' +
               '({' +
               '    title: document.title,' +
               '    description: meta || ""' +
               '});';
    chrome.tabs.executeScript({
        code: code
    }, function(results) {
        if (!results) {
            // An error occurred at executing the script. You've probably not got
            // the permission to execute a content script for the current tab
            return;
        }
        var result = results[0];
        // Now, do something with result.title and result.description
    });
    

    在第一行,我找到了&lt;meta name="description"&gt; 元素。在第二行,如果元素存在,我会读取其 content 属性的值。
    chrome.tabs.executeScript 的回调接收最后一个表达式的返回值,所以我在代码末尾放了一个对象字面量(用括号括起来)。

    【讨论】:

    • 是的,我是菜鸟。也许这从这里很明显,但我试图将标题和元返回到我的扩展程序中的两个输入字段。所以标题将是一个输入的值,而元将是另一个输入的值。从这一点开始我该怎么做? executeScript 使其中的所有 js 都在当前选项卡上执行,而不是在我的扩展程序上执行。
    • @user2879869 那么,您不知道如何继续// Now, do something with result.title and result.description?你已经有什么代码了?例如,如果您有 &lt;input id="title"&gt; 之类的内容,则可以使用 document.getElementById('title').value = result.title;。编辑:executeScript 中的 code 在选项卡的上下文中执行,但它的回调在原始上下文中运行,可能是您的扩展程序的弹出窗口。
    • 所以用document.getElementById('title').value = result.title;替换// Now, do something with result.title and result.description
    • @user2879869 是的,前提是您有一些 ID 为 title 的 HTML,即 &lt;input type="text" id="title"&gt;
    • 这是我现在得到的 Uncaught ReferenceError: result is not defined 感谢您的帮助,我是 Javascript 的新手。
    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    相关资源
    最近更新 更多