使用Javascript查找元“描述”

时间:2014-02-27 10:35:57

标签: javascript google-chrome-extension

我试图传递标签对象tabout,以便找到网页的说明和标题。

当我用一些断点调试代码时,它返回了值,但是当我运行它时,它没有返回描述。

代码有问题吗?

  function computeDescription(tabout)
          {
            var code = 'var meta = document.querySelector("meta[name=\'description\']");' + 
                       'if (meta) meta = meta.getAttribute("content");' +
                       '({' +
                       '    title: document.title,' +
                       '    description: meta || ""' +
                       '});';

            var desc;
            var message = document.querySelector('#message');

            chrome.tabs.executeScript(tabout.id,{code: code}, function(results) {

            if (chrome.extension.lastError) {
            message.innerText = 'There was an error injecting script :\n'+chrome.extension.lastError.message;
            }

            if (!results) {
             return;
            } 

        var result = results[0];
        // Now, do something with result.title and result.description
        console.log(result.title);
        console.log(result.description);
        desc=result.description;

      });

   return desc;

 }

1 个答案:

答案 0 :(得分:0)

看起来你假设你给executeScript的回调将在computeDescription返回之前执行。这不是真的; executeScript异步执行,并且在computeDescription返回之前,您的回调将从不运行。

为了解决这个问题,您需要采用异步模型来定义computeDescription。不是返回值,而是采用回调参数并在数据就绪时调用它。

function computeDescription(tabout, callback) {
   var code = 'var meta = document.querySelector("meta[name=\'description\']");' + 
              'if (meta) meta = meta.getAttribute("content");' +
              '({' +
              '    title: document.title,' +
              '    description: meta || ""' +
              '});';
   var message = document.querySelector('#message');
   chrome.tabs.executeScript(tabout.id, {code: code}, function(results) {
     if (chrome.extension.lastError) {
       message.innerText = 'There was an error injecting script :\n'+chrome.extension.lastError.message;
     }
     if (!results) {
       callback();
     }
     callback(results[0].description);
  });
}

然后你的用法同样从

转换
console.log('Le description is: ' + computeDescription(tab));

computeDescription(tab, function(description) {
  console.log('Le description is: ' + description);
});